任何匹配模式的方法,要么在某个字符之前,要么在某个字符之后

Any way to match a pattern EITHER preceded OR followed by a certain character?

本文关键字:字符 之后 模式 任何匹 方法      更新时间:2023-09-26

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

"ABC"咔嚓"支链氨基酸"驾驶室"拉克布"啦"巴克尔"

但不是以下任何一项:

"拉布克尔"啪"RBCAR"

则表达式可以做到这一点吗?

最简单的方法是使用交替:

/^(?:[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

一些正则表达式引擎支持条件,但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 中的另一种解决方案是使用否定的前瞻断言:

/^(?: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