javascript - 有什么方法可以匹配某个字符之前或之后的模式吗?

标签 javascript regex

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

'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/

相关文章:

java - 正则表达式匹配 "four characters, followed by an unknown No of digits."

java - 如何在java中使用正则表达式验证字符串

php - 有没有比将它放在 PHP 数组中更好的方法来隐藏和存储 JQuery/JavaScript 应用程序的只读数据?

javascript - 使用 .parent 选择 div

javascript - Dojo domConstruct.create

python-3.x - 去除 Pandas 列中特定字符左侧的字符

regex - 使用正则表达式匹配自定义字符串

javascript - Express、通配符子域和 sendFile()

javascript - 使用 for 循环在 JavaScript 中填充二维数组

java - 正则表达式:我想使用正则表达式来操作/更改特定短语。