Question

I'm trying to write a regular expression to test as string. The string must start or end with an alphanumeric character.

eg.

test - OK
test$ - OK
$test - OK
$ - not OK
$test$ - not OK

I can test the beginning with ^\w.*$ and the end with ^\w.*$.

But I can't seem to combine them into something like ^.*\w$ | ^\w.*$.

Does anyone have any ideas or even a better regex for this purpose?

Was it helpful?

Solution

This should work:

^\w.*|.*\w$

OTHER TIPS

The following should work:

/^\w|\w$/

Although \w includes _ so if you only want letters and numbers:

/^[0-9a-zA-Z]|[0-9a-zA-Z]$/

var tests=['test', 'test$', '$test', '$', '$test$'];
var re = /^\w|\w$/;
for(var i in tests) {
  console.log(tests[i]+' - '+(tests[i].match(re)?'OK': 'not OK'));
}

// Results:
test - OK
test$ - OK
$test - OK
$ - not OK
$test$ - not OK
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top