我正在尝试编写一个正则表达式来匹配一组字符,而不考虑顺序。例如:
str = "act"
str.scan(/Insert expression here/)
将匹配:
cat
act
tca
atc
tac
cta
但不匹配ca
, ac
or cata
.
我在 StackOverflow 上阅读了很多类似的问题和答案,但没有找到完全符合我的目标的问题和答案。
为了澄清一点,我正在使用 ruby 并且不想允许重复字符。
这是您的解决方案
^(?:([act])(?!.*\1)){3}$
See it 在 Regexr 上 http://regexr.com?33hh9
^ # matches the start of the string
(?: # open a non capturing group
([act]) # The characters that are allowed and a capturing group
(?!.*\1) # That character is matched only if it does not occur once more, Lookahead assertion
){3} # Defines the amount of characters
$
唯一特别觉得的是前瞻断言 http://www.regular-expressions.info/lookaround.html,保证字符不重复。
^
and $
是匹配字符串开头和结尾的锚点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)