正则表达式 "either/or"但不是 "neither"

标签 regex notepad++

在这里使用 Notepad++ v7.9。
假设 R是一个复杂的正则表达式模式。我现在想匹配 _R , R_ , 或 _R_但不是 R独自的。如何在不明确写入的情况下执行此操作 (_R|R_|_R_) ?这需要将 R 写出 3 次,而且看起来很难看。
我能想到的最接近的是 _?R_?但这也匹配 R单独(实际上等同于它),这对我来说是误报。
中间是 (_?R_|_R_?)但是 R在这里再次重复,虽然少了一次。

最佳答案

您可以使用 If-Then-Else如下:

(_)?R(?(1)_?|_)
Demo .
这使您可以编写 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++ 中工作:
Notepad++ demo

关于正则表达式 "either/or"但不是 "neither",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64680322/

相关文章:

regex - 如何在正则表达式中找到组的所有实例?

字符串内带有可选单词的正则表达式

python - 打印出矩阵中的值

java - 匹配正则表达式模式时如何忽略变音符号?

java - 链接一个元素

python - 编辑 Pandas 脚本以忽略但不删除数据然后匹配和更新+比较以防止浪费保存+切片数据以匹配?

ruby-on-rails - Notepad++ 突出显示 html.erb 文件中 <%= 之后的所有内容

notepad++ - 如何删除重复行(文本文件)?

regex - Notepad++ : selecting text up to matched characters

正则表达式匹配文本后跟大括号