运行regex时出现虚假转义错误

2024-09-26 22:10:34 发布

您现在位置:Python中文网/ 问答频道 /正文

昨天,我得到了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'


Tags: 代码inpyretxtforusrline
2条回答

\x不是有效的特殊序列。如果要匹配文本\x,则需要使用\\x来转义反斜杠;如果需要其他内容,则使用valid one,例如使用\w

这将编译:

re.compile(r'Merging\s+\d+[^=]*=\s*\'\w+@\w+\\x\w+\'\\"')

\x后面必须跟一个十六进制值(即正好两个十六进制数字):

>>> '\x61'
'a'
>>> '\x'
  File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape

如果您想匹配一个文本\x,那么您可以转义反斜杠,这样就不会转义x\\x

相关问题 更多 >

    热门问题