我使用正则表达式来构建在线(字符串)上存在的所有键值对的列表。 我的密钥对语法尊重/匹配以下正则表达式:
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
之前删除字符串。
答案 0 :(得分:4)
这是一个空字节,它存在于原始字符串中。您可能没有看到它,因为您的终端将在您打印字符串时忽略它:
>>> 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')
答案 1 :(得分:1)
只是在你的情况下,process.stdout
迭代器产生的字符串包含空字节。
如果没有要删除的特定字符列表,strip
会删除空格字符。这意味着制表符,换行符,垂直制表符,换页符,回车符和空格。
其中许多与大多数应用程序无关,但如果要删除空字符,则必须明确说明。例如,如果要删除制表符,空格和空值,则应编写
line.strip('\x00\x09\x20')