【问题标题】:Extracting a number with dot and comma using regex使用正则表达式提取带点和逗号的数字
【发布时间】:2015-10-05 22:57:57
【问题描述】:

我已经阅读了很多页面,试图解释如何将regex 用于 Python,但我仍然完全不明白。甚至regex wikire documentation 也帮不了我。我仍然有点困惑:P

我有以下字符串:

string = "|C195|1|Base de Cálculo ST: 2.608,24 - Valor da ST: 163,66|"

我正在尝试仅提取 2.608,24163,66 使用:

st_values = re.findall("\d+[,.]\d+", string)

但是,我的print st_values 的输出是:

['2.608','163,66']

相反,我希望它是

['2.608,24','163,66']

我不想

['195', '1', '2.608,24','163,66']

那么,我该如何使用正则表达式参数的字母汤来提取它们呢?

【问题讨论】:

    标签: python regex string python-2.7 extract


    【解决方案1】:

    如果您想从倒数第二列/字段中提取数字,您可以执行以下操作:

     In: re.findall(r"[0-9,.]+",string.split('|')[-2])      
    Out: ['2.608,24', '163,66']
    

    否则,如果您只使用正则表达式,并且其他列中有类似的数字,您将无法过滤掉它们。

    【讨论】:

      【解决方案2】:

      我建议:

      \b\d{1,3}(?:\.\d{3})*,\d+\b
      

      这是demo

      这是IDEONE code demo

      import re
      p = re.compile(r'\b\d{1,3}(?:\.\d{3})*,\d+\b')
      test_str = "|C195|1|Base de Cálculo ST: 2.608,24 - Valor da ST: 2.608.234,24 12.608.234,24\n  163,66|\nd2.608.234,24\n2.60d8.23d4,24"
      print(re.findall(p, test_str))
      

      【讨论】:

      • 你的答案也适合我的数据,但由于他的方式“更干净”,我发现它更容易阅读和理解,但无论如何谢谢!!
      • @Pardoido:但是如果你有2.600.100,34呢?有一个look here - 它会失败。 \b 是单词边界。如果您还想匹配包含在单词字符中的数字,则可以删除它们。
      【解决方案3】:

      试试这个(这个正则表达式还假设字符串像1,23 是匹配的。)-

      >>> re.findall("\d+(?:\.\d+)?,\d+", string)
      ['2.608,24', '163,66']
      

      Regex demo and Explanation

      【讨论】:

      • @Tushar 嗯,为什么要这样做?它没有 OP 要求的逗号符号
      • 它非常适合我的数据.. 非常感谢,@Kamehameha
      • @Kamehameha,看看已接受答案中的 stribizhev 评论,也许它也会对您有所帮助..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多