Python 3正则表达式问题
因此,我在Python中匹配正则表达式字符串时遇到了一个问题。我已经测试过了,效果很好。但是,当我尝试在代码中执行此操作时,它会给我一个格式错误的正则表达式错误 正则表达式是:“[^\\]\]PW\[”。我希望它能找到字符串]PW[,只要它前面没有反斜杠。 代码如下:Python 3正则表达式问题,python,regex,escaping,character,Python,Regex,Escaping,Character,因此,我在Python中匹配正则表达式字符串时遇到了一个问题。我已经测试过了,效果很好。但是,当我尝试在代码中执行此操作时,它会给我一个格式错误的正则表达式错误 正则表达式是:“[^\\]\]PW\[”。我希望它能找到字符串]PW[,只要它前面没有反斜杠。 代码如下: import sys,re fileList = [] if len(sys.argv) == (0 or 1): fileList = ['tester.sgf'] else: fileList = str(sy
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
回溯(最近一次呼叫最后一次):
文件“C:\Users\Josh\Desktop\New folder\sgflib1.0\test2.py”,第15行,在
对于re.finditer(“[^\\]\]PW\[”,currentSGF)中的迭代:
文件“C:\Python33\lib\re.py”,第210行,在FindItemer中
返回编译(模式、标志).finditer(字符串)
文件“C:\Python33\lib\re.py”,第281行,在编译中
p=sre_compile.compile(模式、标志)
文件“C:\Python33\lib\sre_compile.py”,第491行,在compile中
p=sre_parse.parse(p,标志)
文件“C:\Python33\lib\sre_parse.py”,第747行,在parse中
p=_parse_sub(源,模式,0)
文件“C:\Python33\lib\sre_parse.py”,第359行,在_parse_sub中
itemsappend(_解析(源、状态))
文件“C:\Python33\lib\sre_parse.py”,第485行,在_parse中
引发错误(“正则表达式意外结束”)
sre_constants.error:正则表达式意外结束
感谢您的帮助!您需要使用原始字符串文字或双重转义:
re.finditer(r"[^\\]\]PW\[", currentSGF)
或
否则,Python首先将每个转义序列解释为文本字符串值解释的一部分。re.finditer
将值'[^\]]PW[
否则,\]
和\[
没有特殊意义
请参见Python正则表达式HOWTO中的内容
re.finditer("[^\\\\]\\]PW\\[", currentSGF)