有没有办法编写正则表达式来匹配只包含某些字符的字符串,并且永远不会重复这些字符?我已经使用set来编写一些代码来实现它,但是想知道是否有正则表达式来实现它.
例如,如果我只想要一个包含[A,B,C]的字符串,并且我希望匹配一个永远不会复制任何字符的字符串,例如A,C,AB,AC,BC,ABC等,但从不匹配AA,BB,CC等
谢谢!
解决方法
使用
negative lookahead assertion很容易做到:
^(?!.*(.).*\1)[ABC]+$
完全符合您的描述.
说明:
^ # 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