如何从正则表达式组中提取信息列表?

时间:2017-10-11 00:00:25

标签: regex notepad++ regex-group

我有多个文本,结构如下:

> Record:     24G3KL
> Source:     Whatever
> System Time:Oct 10, 2017 19:01:00 (MST)
> Result:     finalText

在此之前和之后还有更多文字,但没关系。

目标是每当我们遇到> Result: finalText的行时,提取6个字母数字字符值(此处为“24G3KL”)。 “finalText”这个词可以有所不同(例如,它可以是abcdefText或其他任何东西)。我只对值“finalText”感兴趣。

我正在使用以下正则表达式:

([A-Z0-9]{6})(?:.|\n)*(?:\s*finalText)

它工作正常,6个字母数字字符值被提取到正则表达式组1。

在Notepad ++中,我使用“查找”窗口,将我的正则表达式放在“查找内容:”字段中,选择正则表达式,然后单击“在当前文档中查找全部”按钮。

结果是一个如下所示的列表:

Line 85186: > Result:     finalText
Line 86200: > Result:     finalText
Line 87258: > Result:     finalText
Line 87721: > Result:     finalText
Line 87761: > Result:     finalText

我发现这很奇怪,因为“finalText”没有被正则表达式捕获(以“?:”开头)。我希望看到我的第1组(我所有的6个字母数字字符值),而不是那个。

[编辑] 这是我收到的: picture1

在底部的查找结果窗口中,我希望看到6个字母数字字符值而不是“finalText”值......

有办法吗?

3 个答案:

答案 0 :(得分:0)

从我看到它完全匹配,使用$ 1来捕获第一个括号的内容。

答案 1 :(得分:0)

我试过

([A-Z0-9]{6})\n.*\n.*\n> Result:\W*finalText

这似乎有效:

screenshot

这假设Record和Result之间总是有两行。

答案 2 :(得分:0)

  • 控制 + ˚F
  • 找到:> Record:\h*[A-Z0-9]{6}(?:\R.+){2}\R> Result:\h*finalText
  • 检查匹配案例
  • 检查环绕
  • 检查正则表达式
  • 请勿检查. matches newline
  • 在文件中搜索

<强>解释

> Record:\h*    : literally "> Record:" followed by 0 or more horizontal spaces
[A-Z0-9]{6}     : 6 upper case letter or digit
(?:             : non capture group
  \R            : a line break
  .+            : 1 or more any character
){2}            : must be present twice
\R              : a line break
> Result:\h*    : literally "> Result:" followed by 0 or more horizontal spaces
finalText       : literally "finalText"

给定示例的结果:

Search "> Record:\h*[A-Z0-9]{6}(?:\R.+){2}\R> Result:\h*finalText" (2 hits in 1 file)
  new 2 (2 hits)
    Line 1: > Record:     24G3KL
    Line 9: > Record:     RNG3VS