正则表达式或运算符

发布于 2024-09-30 19:12:11 字数 304 浏览 0 评论 0原文

我正在尝试编写一个正则表达式来测试字符串。该字符串必须以字母数字字符开头或结尾。

例如。

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

我可以用 ^\w.*$ 测试开头,用 ^\w.*$ 测试结尾。

但我似乎无法将它们组合成类似 ^.*\w$ | 的东西。 ^\w.*$

有没有人有任何想法,甚至有更好的正则表达式用于此目的?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倒带 2024-10-07 19:12:11

以下内容应该有效:

/^\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

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
与之呼应 2024-10-07 19:12:11

这应该有效:

^\w.*|.*\w$

This should work:

^\w.*|.*\w$
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文