PowerShell 正则表达式:捕获位于多行的两个字符串之间的字符串

PowerShell Regex: Capturing strings between two strings that is on multiple lines

我可能有这样的事情:

FIRST|[some text here] (newline)
[insert text here] (newline)
SECOND|A (newline)

FIRST|[some text here] (newline)
[insert text here] (newline)
SECOND|B (newline)

FIRST|[some text here] (newline)
[insert text here] (newline)
SECOND|A (newline)

FIRST|[some text here] (newline)
[insert text here] (newline)
SECOND|B (newline)

FIRST|[some text here] (newline)
[insert text here] (newline)
SECOND|A (newline)

我只想捕获从 FIRSTSECOND|B 的所有内容,并排除从 FIRSTSECOND|A 的所有内容。 此 post 中的顺序只是一个示例,可能与我正在使用的文件不同。括号中的文本可以是单词、数字、特殊字符等。(换行符)只是告诉你它在不同的行上。 我试过 https://regex101.com/r/CwzCyz/2 (FIRST[\s\S]+SECOND\|B) 但这让我从第一个 FIRST 到最后一个 SECOND|B 这在 regex101.com 中有效,但在我的 PowerShell ISE 应用程序中无效,我猜这是因为我将风格设置为 PCRE(PHP).

FIRST\|(?:(?!SECOND\|[^B])[\S\s])*?SECOND\|B

与第一个不匹配|与 SECOND|A(或任何非 B)关联

https://regex101.com/r/e0CG9B/1

展开

 FIRST \| 
 (?:
      (?! SECOND \| [^B] )
      [\S\s] 
 )*?
 SECOND \| B

如果需要绝对内部 FIRST / SECOND,则必须以不同的方式完成:

FIRST\|(?:(?!(?:FIRST|SECOND)\|)[\S\s])*SECOND\|B

https://regex101.com/r/qoT8U1/1

如果 FIRST 位于行首,而 SECOND|ASECOND|B 位于行首,您可以匹配以下所有不以 [= 开头的行14=]

^FIRST.*(?:\r?\n(?!SECOND\|[AB]\b).*)\r?\nSECOND\|B\b.*

部分

  • ^FIRST.* 行首
  • (?:非捕获组
    • \r?\n(?!SECOND\|[AB]\b)匹配一个换行符,断言不是以SECOND部分开头
    • .* 匹配除换行符以外的任何字符 0 次以上
  • )关闭非捕获组
  • \r?\n 匹配一个换行符
  • SECOND\|B\b.*匹配以SECOND|B
  • 开头的行

Regex demo