用于匹配特定关键字之间文本的正则表达式

Regular expression to match text between specific keywords

我正在寻找与关键字 .if .else .elseif 和 .endif 之间的文本相匹配的正则表达式

示例:

.if CONDITION1
code1
.elseif CONDITION2
code2
.else
code3
.endif

理想情况下,正则表达式只匹配 code1、code2 和 code3,但如果它也匹配关键字后面的文本(CONDITION1、CONDITION2...)也是可以的。

我试过以下正则表达式:

(?:\.if|\.else)(.*?)(?:\.else|\.endif)

但缺少代码 2

Demo

当没有 .elseif and/or .else.

时,正则表达式也必须正常工作

您的问题是您正在有效地尝试捕获从 ifelseif 子句的重叠匹配。您可以通过将正则表达式中的最后一个组改为先行来解决这个问题。

(?:\.if|\.else(?:if)?)(.*?)(?=\.else|\.endif)

Demo on regex101

注意避免捕获条件(或简化 post-processing 它们),您需要更改正则表达式的第一组以允许在 [= 之后的可选 if 15=]。我已经在上面进行了更改,但并不是绝对有必要使正则表达式像您当前那样工作。

如果条件仅出现在与.if/.elseif相同的行上,您可以使用@CarySwoveland 的想法(见评论)来避免捕获条件:

(?:\.if|\.else(?:if)?).*\r?\n([\s\S]*?)(?=\.else|\.endif)

这需要删除 DOTALL 标志。见 demo.

你可以匹配正则表达式

^(?![ \t]*\.(?:if|elseif|else|endif)\b).*

设置了 multiline 标志(导致 ^$ 分别匹配每行的开头,而不是匹配行的开头和结尾字符串).

这匹配所有不以零个或多个空格或制表符开头且后跟 '.if''.elseif''.else''.endif' 的行。如果字符串是下面显示的包含 'code' 的行和空行匹配。

.if CONDITION1
code1  
.elseif CONDITION2
   code2
.code3

     .code4
  .elseif CONDITION3
     code5
  .else
     code6
.endif

Demo

正则表达式可以分解如下

^                           # match beginning of line 
(?!                         # begin a negative lookahead
  [ \t]*                    # match zero or more tabs or spaces  
  \.                        # match a period
  (?:if|elseif|else|endif)  # match one of the strings in the non-capture group
  \b                        # match a word boundary
)                           # end negative lookahead
.*                          # match the line