# Regex pattern
filePattern = re.compile(r'''
(#LPy3THW_Ex)
(\d){1,3}
(_macOS|_Windows)?
(\.mp4)
''', re.VERBOSE)我正在编写一个程序,应该将"LPy3THW_Ex6.mp4“简化为"ex6.mp4”。当我运行它时,下面是错误消息。我不知道是什么问题,以及如何解决它。
Traceback (most recent call last):
File "file_rename.py", line 13, in <module>
''', re.VERBOSE)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 233, in compile
return _compile(pattern, flags)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 301, in _compile
p = sre_compile.compile(pattern, flags)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_compile.py", line 562, in compile
p = sre_parse.parse(p, flags)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 855, in parse
p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 416, in _parse_sub
not nested and not items))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 768, in _parse
source.tell() - start)
sre_constants.error: missing ), unterminated subpattern at position 2 (line 2, column 2)发布于 2018-05-09 20:53:43
当前的错误是由于#符号在使用re.VERBOSE选项编译的regex模式中启动内联注释。
您应该转义它(如果#应该以文字散列字符的形式出现在字符串中)或者删除它(如果在该上下文中字符串中不需要符号)。还有,acc.对于示例输入/输出,您应该删除#并重新排列捕获组,可能如下所示:
filePattern = re.compile(r'''^
LPy3THW_
(
Ex\d{1,3}
(?:_macOS|_Windows)?
\.mp4
)
$''', re.VERBOSE)
print(filePattern.sub(r"\1", s).lower())
# => ex6.mp4注意,(\d){1,3}创建一个重复捕获组,并且只存储组中的最后一个数字。我添加了锚来匹配整个字符串,只是为了演示目的(因为我在这里使用re.sub )。
但是,您可能只需将_分成2部分,并得到最后一项:
s.split('_', 2)[-1].lower() # => ex6.mp4见Python演示
https://stackoverflow.com/questions/50261636
复制相似问题