【问题标题】:Python regular expression with [:numeric:]带有 [:numeric:] 的 Python 正则表达式
【发布时间】:2009-06-15 01:05:18
【问题描述】:

我在使用 Python 时遇到了一些问题,给了我一个意想不到的结果。这是一个示例代码:

number = re.search(" [0-9] ", "test test2 test_ 2 333")
print number.groups()

number = re.search(" [[:digit:]] ", "test test2 test_ 2 333")
print number.groups()

在第一个块中,我返回了一个对象,但其中没有任何内容。我认为我应该在哪里得到字符串“2”。

在第二个块中我什至没有得到一个对象,我期望字符串“2”。

当我在 bash 中执行此操作时,一切看起来都很好:

echo "test test2 test_ 2 333" | grep " [[:digit:]] "
echo "test test2 test_ 2 333" | grep " [0-9] "

有人可以帮帮我吗?

【问题讨论】:

    标签: python regex bash


    【解决方案1】:

    groups() 方法返回捕获组。它确实返回组 0,以防这是您所期望的。使用括号来指示捕获组。例如:

    >>> number = re.search(" ([0-9]) ", "test test2 test_ 2 333")
    >>> print number.groups()
    ('2',)
    

    对于您的第二个示例,Python 的 re 模块无法识别“[:digit:]”语法。使用\d。例如:

    >>> number = re.search(r" (\d) ", "test test2 test_ 2 333")
    >>> print number.groups()
    ('2',)
    

    【讨论】:

      【解决方案2】:

      您缺少用于捕获内容以与 groups()(和其他)函数一起使用的 ()。

      number = re.search(" ([0-9]) ", "test test2 test_ 2 333")
      print number.groups()
      

      这不起作用,因为 python 不支持 [[:number:]] 表示法

      number = re.search(" ([[:digit:]]) ", "test test2 test_ 2 333")
      print number.groups()
      

      【讨论】:

        【解决方案3】:

        这就是你要找的吗?

        >>> re.findall(r'([0-9])', "test test2 test_ 2 333")
        ['2', '2', '3', '3', '3']
        

        【讨论】:

        • 效果很好。在我等待的时候,我一直在努力,发现“re.finditer”也很好用。顺便说一句,我刚刚意识到 Python 不支持 POSIX 字符类。
        • 很高兴您能解决剩下的问题!其他答案要全面得多。 (我被意外拉开,没有机会详细说明。)
        • 事实上,为了更大的利益,我会要求您接受 Laurence Gonsalves 的回答(如果可能的话):stackoverflow.com/questions/994178/…
        【解决方案4】:
        number = re.search(" [0-9] ", "test test2 test_ 2 333")
        print number.group(0)
        

        groups() 只返回第 1 组及以上的组(如果您习惯于其他语言,那就有点奇怪了)。

        【讨论】:

          【解决方案5】:

          .groups() 返回匹配括号内的值。此正则表达式没有任何由括号定义的区域,因此组不返回任何内容。你想要:

          m = re.search(" ([0-9]) ", "test test2 test_2 333") m.groups() ('2',)

          【讨论】:

          • @adam:很好的答案!提示:尝试使用语法高亮突出显示您的代码并按 ctrl-k 以使您的代码正确格式化。
          猜你喜欢
          • 1970-01-01
          • 2012-05-14
          • 1970-01-01
          • 1970-01-01
          • 2019-01-19
          • 2010-09-28
          • 2012-03-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多