【问题标题】:Python regex: How can I match start of string in a selection?Python regex:如何匹配选择中的字符串开头?
【发布时间】:2012-03-22 16:19:11
【问题描述】:

我想匹配一些前面有非数字或字符串开头的数字。

由于括号内的插入符号没有特殊含义,我不能使用那个,所以我检查了the reference,发现了另一种形式\A

但是,当我尝试使用它时出现错误:

>>> s = '123'
>>> re.findall('[\D\A]\d+', s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 177, in findall
    return _compile(pattern, flags).findall(string)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 245, in _compile
    raise error, v # invalid expression
sre_constants.error: internal: unsupported set operator

我做错了什么?

【问题讨论】:

  • 您不能只在括号外使用插入符号,像这样吗? ^[A-Za-z]+? 同样,括号内没有特殊含义的插入符号也不是完全正确的。如果插入符号是括号内的第一个字符,它将否定里面的字符集(说匹配除[^...] 之外的所有字符
  • "一些数字前面有一个非数字或在字符串的开头" - 这不是说所有数字吗?只需使用\d+...
  • @lzkata:真正的用例更复杂。这只是一个简化。
  • 我其实也有差不多的问题stackoverflow.com/questions/16257370/…>

标签: python regex


【解决方案1】:

您可以使用否定的lookbehind:

(?<!\d)\d+

您的问题是您在字符类中使用\A(零宽度断言),用于匹配单个字符。你可以改写成(?:\D|\A),但是后面的代码更好。

【讨论】:

    【解决方案2】:

    默认情况下,正则表达式中的重复是贪婪的,因此使用 re.findall() 和正则表达式 \d+ 会得到你想要的:

    re.findall(r'\d+', s)
    

    附带说明一下,在编写正则表达式时应该使用原始字符串,以确保正确解释反斜杠。

    【讨论】:

    • 在这个简化的用例中,是的。在真正需要匹配字符串开头的实际用例中,这是不可能的。感谢原始字符串提示。
    猜你喜欢
    • 2019-08-06
    • 2016-02-10
    • 2012-08-26
    • 2018-02-24
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多