例如,我想匹配以下所有字符串:
'abc' 'CBA' 'BCA' '出租车' '拉克' 'rcab' '巴克尔'
但不包括以下任何一项:
“拉布” 'rbacr' 'rbcar'
这可以通过正则表达式实现吗?
最佳答案
最简单的方法是使用 alternation :
/^(?:[abc]{3}r?|r[abc]{3})$/
说明:
^ # Start of string
(?: # Non-capturing group:
[abc]{3} # Either match abc,cba,bac etc.
r? # optionally followed by r
| # or
r # match r
[abc]{3} # followed by abc,cba,bac etc.
) # End of group
$ # End of string
一些正则表达式引擎支持 conditionals ,但 JavaScript 并不在其中。但在 .NET 中,您可以这样做
^(r)?[abc]{3}(?(1)|r?)$
无需在同一个正则表达式中编写两次字符类。
说明:
^ # Start of string
(r)? # Match r in group 1, but make the group optional
[abc]{3} # Match abc,cab etc.
(?(1) # If group 1 participated in the match,
# then match nothing,
| # else
r? # match r (or nothing)
) # End of conditional
$ # End of string
JavaScript 中的另一个解决方案是使用 negative lookahead assertion :
/^(?:r(?!.*r$))?[abc]{3}r?$/
说明:
^ # Start of string
(?: # Non-capturing group:
r # Match r
(?!.*r$) # only if the string doesn't end in r
)? # Make the group optional
[abc]{3} # Match abc etc.
r? # Match r (optionally)
$ # End of string
关于javascript - 有什么方法可以匹配某个字符之前或之后的模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20031308/