假设我有这个:
[a-zA-Z0-9., -&:]+
允许使用字母数字字母和一些特殊字符(逗号、点、破折号等)一次或多次。但现在,我只想在还有字母数字字母时允许使用这些特殊字符:
a-b, c
: ok
.a:
: ok
,-.
: 不好
,
: 不好
我尝试了一些方法,但仍然无法找到一种方法。我怎么做?
如果你想确保其中至少有一个字母数字字符,你可以使用:
[a-zA-Z0-9., &:-]*[a-zA-Z0-9][a-zA-Z0-9., &:-]*
This is basically zero or more of your current pattern (slightly modified(a)), followed by one alphanumeric, followed by zero or more of your current pattern again. This guarantees no match unless the string has one or more alphanumerics.
您可能还想考虑将^
and $
如果您使用允许部分匹配的正则表达式函数,则在模式末尾添加标记。没有它,你可以匹配类似的东西<some-invalid-character>A
. This may如果您使用“完全匹配”功能,则没有必要。
(a) The modification, as per comments in another answer, is to move the -
to the end of the regex to have it treated as a literal hyphen rather than a character range.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)