正则表达式匹配超过允许的字符
我试图验证给定的字符串仅包含字母、数字、空格和一组符号中的字符 (!-?():&,;+
)。到目前为止,这是我所拥有的:
/^[a-zA-Z0-9 !-?\(\):&,;\+]+$/
现在这有点起作用,但它也接受其他字符。例如,包含 *
或 #
的字符串进行验证。我认为表达式开头的 ^
和结尾的 $
意味着它将匹配整个字符串。我做错了什么?
谢谢。
I am trying to validate that the given string contains contains only letters, numbers, spaces, and characters from a set of symbols (!-?():&,;+
). Here is what I have so far:
/^[a-zA-Z0-9 !-?\(\):&,;\+]+$/
Now this works somewhat but it accepts other characters as well. For example, strings containing *
or #
validate. I thought that the ^
at the beginning of the expression and the $
at the end meant that it would match the whole string. What am I doing wrong?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
- 你放置它的地方不太好!如果您想将 - 放置在字符类中,请确保将其放置在第一个或最后,例如,
否则它将采用 ! 的范围。直到 ?无论这个范围如何...取决于您的正则表达式机器。
最后,特殊字符在字符类中并不特殊。所以没有必要逃避其中的大多数:
The - is not nice where you placed it! If you want to place - inside a character class be sure to either place it first or last e.g.
Otherwise it will take the range of ! until ? whatever this range maybe...Depends on your regex machine.
Finally special characters are not special inside character classes. So no need to escape most of them :
您已在字符类中指定了一个“范围”:
表示
!
和?
之间的所有 ASCII 符号
http://www.regular-expressions.info/charclass.html
你需要转义减号
-
和\
反斜杠。 (OTOH,字符类中+
和(
和)
之前的反斜杠是多余的。)You have specified a "range" within your character class:
Means all ASCII symbols between
!
and?
http://www.regular-expressions.info/charclass.html
You need to escape the minus
-
with a\
backslash. (OTOH the backslash is redundant before the+
and(
and)
within a character class.)