【问题标题】:Regex error: nothing to repeat at position 0 [duplicate]正则表达式错误:在位置 0 没有可重复的内容 [重复]
【发布时间】:2021-02-27 15:57:27
【问题描述】:

我正在尝试解析我的正则表达式失败并出现主题中提到的错误的文本。

在下面的代码中我只使用了那部分,我不知道它为什么会失败!任何帮助将不胜感激

虽然我在 SO 线程中看到了这个错误,但这对我来说似乎不同

import re
t = '++cnt;'

re.sub('++cnt','@'.join(c for c in '++cnt'),t)

error                                     Traceback (most recent call last)
<ipython-input-482-2b724235a79b> in <module>
      1 t = '++cnt;'
      2 
----> 3 re.sub('+cnt','@'.join(c for c in '++cnt'),t)

~/anaconda3/lib/python3.8/re.py in sub(pattern, repl, string, count, flags)
    208     a callable, it's passed the Match object and must return
    209     a replacement string to be used."""
--> 210     return _compile(pattern, flags).sub(repl, string, count)
    211 
    212 def subn(pattern, repl, string, count=0, flags=0):

~/anaconda3/lib/python3.8/re.py in _compile(pattern, flags)
    302     if not sre_compile.isstring(pattern):
    303         raise TypeError("first argument must be string or compiled pattern")
--> 304     p = sre_compile.compile(pattern, flags)
    305     if not (flags & DEBUG):
    306         if len(_cache) >= _MAXCACHE:

~/anaconda3/lib/python3.8/sre_compile.py in compile(p, flags)
    762     if isstring(p):
    763         pattern = p
--> 764         p = sre_parse.parse(p, flags)
    765     else:
    766         pattern = None

~/anaconda3/lib/python3.8/sre_parse.py in parse(str, flags, state)
    946 
    947     try:
--> 948         p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
    949     except Verbose:
    950         # the VERBOSE flag was switched on inside the pattern.  to be

~/anaconda3/lib/python3.8/sre_parse.py in _parse_sub(source, state, verbose, nested)
    441     start = source.tell()
    442     while True:
--> 443         itemsappend(_parse(source, state, verbose, nested + 1,
    444                            not nested and not items))
    445         if not sourcematch("|"):

~/anaconda3/lib/python3.8/sre_parse.py in _parse(source, state, verbose, nested, first)
    666                 item = None
    667             if not item or item[0][0] is AT:
--> 668                 raise source.error("nothing to repeat",
    669                                    source.tell() - here + len(this))
    670             if item[0][0] in _REPEATCODES:

error: nothing to repeat at position 0


【问题讨论】:

  • + 在正则表达式中不是文字。它的意思是“一个或多个前一个字符”。如果你想要它的字面意思,你必须逃避它:re.sub(r"\+\+cnt", ....

标签: python regex


【解决方案1】:

在正则表达式中+ 表示前面的匹配组需要重复一次或多次。您将+ 放在匹配模式的开头,因此没有可以重复的内容。看来您想匹配字符+。如果是这样,那么+需要被转义,你的匹配模式应该是'\+\+cnt'

【讨论】:

  • 可能还建议对任何正则表达式使用原始字符串 r'...'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
  • 2017-08-27
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多