简体   繁体   English

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

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

For instance, I'd like to match all of the following strings: 例如,我想匹配以下所有字符串:

'abc' 'cba' 'bca' 'cab' 'racb' 'rcab' 'bacr' 'abc''cba''bca''cab''racb''rcc''bacr'

but NOT any of the following: 但不是以下任何一种:

'rabcr' 'rbacr' 'rbcar' 'rabcr''rbacr''rbcar'

Is this possible with regex? 正则表达式可以实现吗?

The easiest way would be to use alternation : 最简单的方法是使用交替

/^(?:[abc]{3}r?|r[abc]{3})$/

Explanation: 说明:

^         # 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

Some regex engines support conditionals , but JavaScript is not among them. 一些正则表达式引擎支持条件 ,但JavaScript不在其中。 But in .NET, you could do 但在.NET中,你可以做到

^(r)?[abc]{3}(?(1)|r?)$

without the need to write your character class twice in the same regex. 无需在同一个正则表达式中编写两次字符类。

Explanation: 说明:

^        # 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

Another solution in JavaScript would be to use a negative lookahead assertion : JavaScript中的另一个解决方案是使用负前瞻断言

/^(?:r(?!.*r$))?[abc]{3}r?$/

Explanation: 说明:

^         # 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM