gpt4 book ai didi

Python 3 正则表达式问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:08 26 4
gpt4 key购买 nike

所以我在 Python 中匹配正则表达式字符串时遇到问题。我已经在 http://regex101.com/ 上测试过它而且效果很好。但是,当我尝试在代码中执行此操作时,它会给出格式错误的正则表达式错误

正则表达式为:“[^\\]\]PW\[”。我想让它找到字符串 ]PW[,只要它前面不以反斜杠开头。代码如下:

import sys,re
fileList = []
if len(sys.argv) == (0 or 1):
fileList = ['tester.sgf']
else:
fileList = str(sys.argv)
for sgfName in fileList:
print(sgfName)
currentSGF = open(sgfName,'r').read()
currentSGF = currentSGF.replace("\r","") #clean the string
currentSGF = currentSGF.replace("\n","")
for iterations in re.finditer("[^\\]\]PW\[",currentSGF): #here's the issue
print(iterations.start(0), iterations.end(0), iterations.group())

我得到的错误是:

Traceback (most recent call last):
File "C:\Users\Josh\Desktop\New folder\sgflib1.0\test2.py", line 15, in <module>
for iterations in re.finditer("[^\\]\]PW\[",currentSGF):
File "C:\Python33\lib\re.py", line 210, in finditer
return _compile(pattern, flags).finditer(string)
File "C:\Python33\lib\re.py", line 281, in _compile
p = sre_compile.compile(pattern, flags)
File "C:\Python33\lib\sre_compile.py", line 491, in compile
p = sre_parse.parse(p, flags)
File "C:\Python33\lib\sre_parse.py", line 747, in parse
p = _parse_sub(source, pattern, 0)
File "C:\Python33\lib\sre_parse.py", line 359, in _parse_sub
itemsappend(_parse(source, state))
File "C:\Python33\lib\sre_parse.py", line 485, in _parse
raise error("unexpected end of regular expression")
sre_constants.error: unexpected end of regular expression

感谢您的帮助!

最佳答案

您需要使用原始字符串文字或将所有转义符加倍:

re.finditer(r"[^\\]\]PW\[", currentSGF)

re.finditer("[^\\\\]\\]PW\\[", currentSGF)

否则,Python 首先将每个转义序列解释为文字字符串值解释的一部分。 re.finditer 看到值 '[^\]]PW[,否则为 \]\[没有特殊意义。

参见The Backslash Plague在 Python 正则表达式 HOWTO 中。

关于Python 3 正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24842883/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com