任何方式匹配模式EITHER先于OR后跟某个字符?

时间:2013-11-17 13:37:17

标签: javascript regex

例如,我想匹配以下所有字符串:

'ABC' 'CBA' 'BCA' '出租车' 'racb' 'rcab' 'BACR'

但不是以下任何一种:

'rabcr' 'rbacr' 'rbcar'

这是否可以使用正则表达式?

1 个答案:

答案 0 :(得分:3)

最简单的方法是使用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