我使用正则表达式来构建行(字符串)上存在的所有键值对的列表。 我的 key 对语法尊重/匹配以下正则表达式:
re.compile("\((.*?),(.*?)\)")
通常我必须解析如下字符串:
(hex, 0x123456)
如果我使用解释器就可以了
str = "(hex,0x123456)"
>>> KeyPair = re.findall(MyRegex, str)
>>> KeyPair
[('hex', '0x123456')]
但是当我在 linux 下使用该代码解析命令行输出时,我得到:
[('hex', '0x123456\x00')]
它来自下面的代码
KeyPayList = []
# some code ....
process = subprocess.Popen(self.cmd_line, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, stdin=subprocess.PIPE)
# here we parse the output
for line in process.stdout:
if line.startswith(lineStartWith):
KeyPair = re.findall(MyRegex, line.strip())
KeyPayList.append(KeyPair)
你知道为什么我在捕获的第二组中得到那个奇怪的 \x00
吗?
请注意,我已经尝试在调用 findall
之前剥离字符串。
最佳答案
这是一个空字节,它存在于您的原始字符串中。你可能没有看到它,因为当你打印字符串时你的终端会忽略它:
>>> s = "(hex,0x123456\x00)"
>>> print s
(hex,0x123456)
用于容器内容(例如您在此处打印的元组的内容)的 Python repr()
函数确实显示了它:
>>> print repr(s)
'(hex,0x123456\x00)'
您的正则表达式只是返回该空字节,因为它存在于您的原始字符串中:
>>> import re
>>> s = "(hex,0x123456\x00)"
>>> yourpattern = re.compile("\((.*?),(.*?)\)")
>>> yourpattern.search(s).groups()
('hex', '0x123456\x00')
如果您要删除它,正则表达式引擎也不会返回它:
>>> yourpattern.search(s.replace('\x00', '')).groups()
('hex', '0x123456')
关于python - 为什么正则表达式 findall 返回一个奇怪的\x00,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26219901/