昨天,我得到了regex匹配方面的帮助,它作为一个独立程序运行得很好。但当我输入这段代码时,我得到了“虚假的转义错误”。代码和回溯如下。你能告诉我我做错了什么吗?
#!/usr/bin/env python
import re
sf = open("a.txt","r")
out = open("b.txt","w")
regex = re.compile(r'Merging\s+\d+[^=]*=\s*\'\w+@\w+\x\w+\'\\"')
for line in sf:
m = regex.findall(line)
for i in m:
print >> out,line,
回溯是:
Traceback (most recent call last):
File "match.py", line 6, in <module> regex = re.compile(r'Merging\s+\d+[^=]*=\s*\'\w+@\w+\x\w+\'\\"') File "/usr/lib/python2.7/re.py", line 190, in compile return _compile(pattern, flags) File "/usr/lib/python2.7/re.py", line 242, in _compile raise error, v # invalid expression sre_constants.error: bogus escape: '\\x'
\x
不是有效的特殊序列。如果要匹配文本\x
,则需要使用\\x
来转义反斜杠;如果需要其他内容,则使用valid one,例如使用\w
。这将编译:
\x
后面必须跟一个十六进制值(即正好两个十六进制数字):如果您想匹配一个文本
\x
,那么您可以转义反斜杠,这样就不会转义x
:\\x
。相关问题 更多 >
编程相关推荐