难以形成正则表达式

发布于 2025-01-11 17:57:34 字数 284 浏览 0 评论 0原文

我正在尝试检查一个字符串,以确保它只包含小写和大写字母、数字 0-9、下划线、破折号和句点。

我一直用于字母、数字、下划线和破折号的正则表达式工作正常,如下所示:

“[^a-zA-Z0-9_-]”

不过,我在添加空格和句点检查时遇到了困难。

我试过:

“[^a-zA-Z0-9_-]”(在破折号后添加一个空格) “[^a-zA-Z0-9_-\s\.]”(试图转义空白字符)

我也尝试过将 \s 和 \.在主区块之外以及自己的区块中。

感谢您的任何建议。

I'm trying to check a string to make sure that it only contains lowercase and uppercased letters, the digits 0-9, underscores, dashes and periods.

The regular expression I've been using for letter, numbers, underscores and dashes works fine and is this:

"[^a-zA-Z0-9_-]"

I'm having difficulty adding the check for spaces and periods though.

I've tried:

"[^a-zA-Z0-9_- ]" (added a space after the dash)
"[^a-zA-Z0-9_-\s\.]" (trying to escape a white space character)

I've also tried putting the \s and \. outside of the main block and also in blocks of their own.

Thanks for any advice.

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

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

发布评论

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

评论(2

酒中人 2025-01-18 17:57:34

连字符(代表字符)必须位于(否定)字符类的开头或结尾。

在字符类中,句点是普通字符,不需要转义。

let pattern = "[^a-zA-Z0-9_. -]+"

A hyphen (representing the character) must be at the beginning or at the end of the (negating) character class.

Inside a character class the period is a normal character, it doesn't need to be escaped.

let pattern = "[^a-zA-Z0-9_. -]+"
み青杉依旧 2025-01-18 17:57:34

添加具有特殊含义的字符时要小心:您忘记了连字符。
我认为这就是您正在寻找的:

"[\^ a-zA-Z0-9_,\.\-]"

Be careful about adding characters which have a special meaning: you forgot the hyphen.
I think that this is what you are looking for:

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