我正在尝试编写正则表达式以测试字符串。字符串必须以字母数字开始或结束。

例如。

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

我可以测试开始 ^\w.*$ 最后 ^\w.*$.

但是我似乎不能将它们结合到类似 ^.*\w$ | ^\w.*$.

有人有任何想法,甚至是更好的正则是为此目的吗?

有帮助吗?

解决方案

这应该有效:

^\w.*|.*\w$

其他提示

以下应该有效:

/^\w|\w$/

虽然 \w 包括 _ 因此,如果您只想要字母和数字:

/^[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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top