假设我有一个文本文件,其内容类似于以下内容:

021 Line one of section A.
021 Line two of Section A.
021 Line three of section A.
021 Part two of Line three of Section A.
021 We just skipped line four, but that's okay.
021 Back to line six.
Non-formatted lines to be ignored. This can be from 0 lines, to any number of lines, and the content can be any text.
033 Line 1 of Section B
033 Line 2 of Section B
033 Okay, that's enough.

在正则表达式中,是否有可能给我两个组,第一组包含以021开头的所有行,第二组包含以033开头的所有行?

线标记会有所不同,但总是为\d{3}

分析解答

您可以捕获捕获组中开头的数字,并在重复时使用反向引用\1到该组。

这将为您提供开头的数字相同的匹配项。

^(\d{3}) .*(?:\r?\n\1.*)*

正则表达式demo