我正在尝试解析一个文本,其中我的正则表达式因主题中提到的错误而失败。
在下面的代码中,我仅使用该部分,我不知道为什么它会失败!任何帮助,将不胜感激
尽管我在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
regex+
表示前面的匹配组需要重复一次或多次。您将其放置+
在比赛模式的开头,因此没有可以重复的内容。看来您想匹配角色+
。如果是这样,则+
需要转义,并且您的匹配模式应为'\ + \ + cnt'
进行此更改后,re.sub(r'\+\+cnt','@'.join(c for c in '++cnt'),t)
将不会产生任何效果,因为如果t='++cnt;'
这样,'@'.join(c for c in '++cnt'),t)
则将给出'+@+@c@n@t;'
不包含“ ++ cnt”的字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句