有没有办法编写正则表达式来匹配仅包含某些字符的字符串,并且从不重复这些字符?我已经使用一组代码编写了一些代码来实现此目的,但想知道是否有正则表达式的方法可以做到这一点。
例如,如果我只想要一个包含 [A,B,C] 的字符串,并且我想匹配一个从不重复任何这些字符的字符串,例如 A、B、C、AB、AC、B、BC 、ABC 等,但从不匹配 AA、BB、CC 等
Thanks!
这很容易做到否定前瞻断言 http://www.regular-expressions.info/lookaround.html:
^(?!.*(.).*\1)[ABC]+$
与您描述的完全一致。
Test it 住在 regex101.com http://regex101.com/r/fN3eR1/2.
解释:
^ # Start of the string
(?! # Assert that it's impossible to match...
.* # Any number of characters (including zero)
(.) # followed by one character (remember this one in group 1)
.* # that's followed by any number of characters
\1 # and the same character as before
) # End of lookahead
[ABC]+ # Match one or more characters from this list
$ # until the end of the string
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)