【问题标题】:Regular expression to return all match occurrences返回所有匹配项的正则表达式
【发布时间】:2020-12-02 08:47:54
【问题描述】:

我有如下文字-

02052020 02:40:02.445: Vacation Allowance: 21; nnnnnn Vacation Allowance: 22;nnn

我想在 Python 中提取以下内容-

Vacation Allowance: 21
Vacation Allowance: 22

基本上,我想提取所有出现的“Vacation Allowance:”以及后缀为;的数值

我正在使用下面的正则表达式-

(.*)(Vacation Allowance:)(.*);(.*)

下面是完整的 Python 代码-

import re

text = '02/05/2020 Vacation Allowance: 21; 02/05/2020 Vacation Allowance: 22; nnn'

pattern = re.compile(r'(.*)(Vacation Allowance:)(.*);(.*)')

for (a,b,c,d) in re.findall(pattern, text):
    print(b, " ", c)

这并不是所有的出现,而是只给出最后一次出现。当前输出是-

Vacation Allowance: 22

您能否评论一下我如何提取所有匹配项?

【问题讨论】:

  • 只要使用\bVacation Allowance:\s*\d+;
  • 你想用什么语言实现这个?
  • 您使用什么语言/工具?来自regex tag info:“由于正则表达式尚未完全标准化,所有带有此标签的问题还应包含一个指定适用的编程语言或工具的标签。”
  • 我在 Python 中需要这个。
  • @anubhava- 感谢您的评论。我试过你的建议,但它不起作用。顺便说一句,我正在 Python 中尝试这个。我现在已经在原来的问题中澄清了这一点。

标签: python regex regex-group


【解决方案1】:

问题在于使用的正则表达式。 (.*) 块接受的字符串比你意识到的要多 - .* 被称为贪婪操作,它会在匹配的同时尽可能多地消耗字符串。这就是为什么您只能看到一个输出。

建议匹配Vacation Allowance:\s*\d+; 或类似的内容。

text = '02/05/2020 Vacation Allowance: 21; 02/05/2020 Vacation Allowance: 22; nnn'
m = re.findall('Vacation Allowance:\s*(\d*);', text, re.M)
print(m)

结果:['21', '22']

【讨论】:

  • 感谢 Petriborg 澄清 (.*) 是一个贪婪的操作。我已经转向使用字符串函数(而不是正则表达式),因为还有其他模式要匹配,并且值并不总是数字。我将此标记为正确答案,因为它正确突出了问题并引导我寻找替代解决方案。
【解决方案2】:

在 Javascript 中是'text'.match(/\bVacation Allowance: \d+/g)

你需要全局属性g

【讨论】:

  • 感谢您的回复。这就是我在 Python 中使用您的建议的方式,但它不起作用。没有结果。 import re text = '02/05/2020 0假期津贴:21; 02/05/2020 假期津贴:22; nnn' pattern = re.compile(r'\bVacation Allowance: \d+/g') print(re.findall(pattern, text))
  • 哦,Python。它是 pattern = re.compile(r'\bVacation Allowance: \d+'),在 Python 中不是 /g,你可以使用 findall。
  • 谢谢灭霸。我已经转向使用字符串函数(而不是正则表达式),因为还有其他模式要匹配,并且值并不总是数字。使用正则表达式,我不得不使用 .*,正如 @Petriborg 所澄清的那样,这是一个贪婪的操作,会导致问题。
猜你喜欢
  • 2021-10-12
  • 1970-01-01
  • 2018-02-18
  • 2012-12-22
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多