I'm trying to put together a js flavor of regex to match a string like in the following examples where there may be a whitespace at the front or back of the string, or both front and back. But not within the string
Examples:
'Z5LW-KRT2' MATCH
' Z5LW-krt2' MATCH
'Z5LW-KRT2 ' MATCH
' Z5LW-KRT2 ' MATCH
' Z5LW-K RT2 ' NO MATCH
So far i have come up with the below which matches if there is no whitespace anywhere, but i cant figure out how to include white space at the beginning or end but not within like in the examples
^[A-Za-z0-9\-] $
CodePudding user response:
You should add \s* to match spaces so the result regex should look like ^\s*[A-Za-z0-9\-] \s*$ and even you can reduce it to ^\s*[\w\-] \s*$ if you want to use the build-in class \w.
CodePudding user response:
Either
^\s*\S \s*$ or ^\s*[A-Za-z0-9\-] \s*$ will do what you need:
^: start of string
\s*: optional whitespace
\S : at least 1 non-whitespace OR
[A-Za-z0-9\-]: match literal character classes
\s*: optional whitespace
$: end of string
let tests = [ 'Z5LW-KRT2' // MATCH
, ' Z5LW-krt2' // MATCH
, 'Z5LW-KRT2 ' // MATCH
, ' Z5LW-KRT2 ' // MATCH
, ' Z5LW-K RT2 ' // NO MATCH
]
let regex1 = /^\s*\S \s*$/
let regex2 = /^\s*[A-Za-z0-9\-] \s*$/
for (test of tests) {
console.log(`[${test}] regex1: ${test.match(regex1)?'MATCH':'NO MATCH'}, regex2: ${test.match(regex2)?'MATCH':'NO MATCH'}`)
}
