【问题标题】:Capture repeated values in a group(regex,python) [duplicate]捕获组中的重复值(正则表达式,python)[重复]
【发布时间】:2022-11-03 22:48:14
【问题描述】:

我的目标是从字符串中提取薪水。我想出了以下正则表达式:

pattern  = r'(CA|Collective agreement) .+ ([0-9]{1,4}[.,][0-9]{1,3}[,]*[0-9]*) .+ ([0-9]{1,4}[.,][0-9]{1,3}[,]*[0-9]*)'
  • (CA|Collective agreement) - 第一组,如果工资是根据集体协议定义的。
  • ([0-9]{1,4}[.,][0-9]{1,3}[,]*[0-9]*) - 是 xx.yyy,zz 形式的薪水(例如 1.950,13 $)
  • .+ 在集体协议和薪水之间匹配任何字符。

我复制了工资组以获取一系列工资。例如:

s = 'Collective agreement from 1.950 $ to 2.500 $'
pattern  = r'(CA|Collective agreement) .+ ([0-9]{1,4}[.,][0-9]{1,3}[,]*[0-9]*) .+ ([0-9]{1,4}[.,][0-9]{1,3}[,]*[0-9]*)'
re.findall(pattern,s)
#[('Collective agreement', '1.950', '2.500')]

我的问题是:是否有更优雅的解决方案来处理薪资范围?似乎一切正常,但看起来并不好。 re 不会捕获组中的重复匹配项(据我所知)

【问题讨论】:

    标签: python regex


    【解决方案1】:

    也许您可以使用 f-strings 来组成您的模式:

    import re
    
    s = "Collective agreement from 1.950 $ to 2.500 $"
    number = r"[0-9]{1,4}[.,][0-9]{1,3}[,]*[0-9]*"
    pattern = rf"(CA|Collective agreement) .+ ({number}) .+ ({number})"
    
    print(re.findall(pattern, s))
    

    印刷:

    [('Collective agreement', '1.950', '2.500')]
    

    【讨论】:

      猜你喜欢
      • 2017-09-13
      • 2011-03-11
      • 2017-01-07
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 2011-10-19
      相关资源
      最近更新 更多