首页 > 解决方案 > RegEx - 每组行一组

问题描述

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

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}.

标签: javaregex

解决方案


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

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

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

正则表达式演示


推荐阅读