这里使用的是Notepad++ v7.9。
假设R
是一个复杂的正则表达式模式,现在我想匹配 _R
、R_
或者 _R_
,但不想匹配单独的R
。如何做到这一点,而不必显式地编写(_R|R_|_R_)
?这需要将R
写三次,看起来很丑陋。
我能想到的最接近的方法是_?R_?
,但它也匹配单独的R
(实际上等同于它),这对我来说是误报。
介于两者之间的是(_?R_|_R_?)
,但这里再次重复了R
,虽然减少了一次。
您可以按照以下方式使用If-Then-Else:
(_)?R(?(1)_?|_)
演示.
这使您只需编写一次R
。
详细说明:
(_)? # An optional capturing group that matches an underscore character.
R # Matches 'R' literally (replace it with your pattern).
(? # If...
(1) # ..the first capturing group is found,...
_? # ..then match zero or one underscore characters (optional).
| # Else (otherwise)...
_ # Match exactly one underscore character (required).
) # End If.
适用于Notepad++:
if
部分会在第一组为 None 时触发,这就是为什么 ?
在第一捕获组之外的原因。 - Wiktor Stribiżew
(?!^R$)_?R_?
- Alireza_?(R)_?\1?_
很有趣。https://regex101.com/r/KKNrJa/1 - MonkeyZeus