【问题标题】:sre_constants.error: multiple repeat at position 2sre_constants.error:在位置 2 多次重复
【发布时间】:2018-05-21 09:27:17
【问题描述】:

我尝试匹配+h之间的所有子字符串,例如+abcd1234h

代码如下:

match = re.match(r'.*+(.*)h.*',line)

错误发生如下,当我运行我的代码时:

File "C:\Program Files\Python\Python36\lib\re.py", line 172, in match
    return _compile(pattern, flags).match(string)

  File "C:\Program Files\Python\Python36\lib\re.py", line 301, in _compile
    p = sre_compile.compile(pattern, flags)

  File "C:\Program Files\Python\Python36\lib\sre_compile.py", line 562, in compi
le
    p = sre_parse.parse(p, flags)

  File "C:\Program Files\Python\Python36\lib\sre_parse.py", line 855, in parse
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)

  File "C:\Program Files\Python\Python36\lib\sre_parse.py", line 416, in _parse_
sub
    not nested and not items))

  File "C:\Program Files\Python\Python36\lib\sre_parse.py", line 619, in _parse
    source.tell() - here + len(this))

sre_constants.error: multiple repeat at position 2

似乎是正则表达式错误,如何解决? .

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:

    通过转义+:

    >>> re.match(r".*\+(.*)h.*", "+abcd1234h").groups()
    ('abcd1234',)
    

    在正则表达式中,+ 具有特殊含义(匹配前面的一个或多个字符)。显然您知道* 表示匹配零个或多个。

    因此,异常会告诉您究竟出了什么问题...表达式包含“多次重复”(*+)

    注意:

    没有必要将re.match 与前导和尾随匹配规则一起使用,您可以更简洁地这样做:

    >>> re.search(r"\+(.*)h", "+abcd1234h").groups()
    ('abcd1234',)
    

    【讨论】:

    • @Rui 如果您觉得此答案有帮助,请点赞并接受答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多