Validation
Trimmed Text Regex
Leading and trailing spaces cause subtle bugs: two names that look identical do not compare as equal, and search indexes treat them as different values. This pattern requires the first character to be a non-whitespace character, and if the text is longer than one character, the last one must be non-whitespace too. Spaces in the middle are allowed, so Ali Test passes while a value with a space before or after it fails. Because the dot does not match newlines, it also rejects multi-line input. Use it in data checks to catch values that were saved without trimming.
Pattern (JavaScript)
/^\S(.*\S)?$/Starts at the start of the line/string, then any character that is not whitespace, then a group (any character, zero or more times, then any character that is not whitespace), optionally (zero or one time), then the end of the line/string.
Examples
Matches
- ✓ hello
- ✓ a
- ✓ Ali Test
Does not match
- ✗ leading
- ✗ trailing
- ✗
Try it
0 matches (JavaScript engine)
hello
a
Ali Test
leading
trailing
Code in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /^\S(.*\S)?$/g;
const text = "hello";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'^\S(.*\S)?$')
text = 'hello'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/^\S(.*\S)?$/';
$text = 'hello';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^\\S(.*\\S)?$");
String text = "hello";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^\S(.*\S)?$`)
text := "hello"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^\S(.*\S)?$");
var text = "hello";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"^\S(.*\S)?$").unwrap();
let text = "hello";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /^\S(.*\S)?$/
text = 'hello'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- Why is the middle part optional?
- A single character is both the first and last character. Making (.*\S) optional lets one-character values pass.
- Does it reject double spaces in the middle?
- No. Only the ends are checked. Combine it with a multiple-spaces check if inner spacing also matters.
- Should I validate or just trim?
- For user input, trimming on save is friendlier. Use this pattern to audit existing data or to enforce clean values in an API.