为什么regex findall返回一个奇怪的x00



我使用正则表达式来构建行(字符串)上所有键值对的列表。我的密钥对语法尊重/匹配以下正则表达式:

 re.compile("((.*?),(.*?))")

通常我必须解析一个字符串,比如:

(hex, 0x123456)

如果我使用翻译,也没问题

str = "(hex,0x123456)"
>>> KeyPair = re.findall(MyRegex, str)
>>> KeyPair
[('hex', '0x123456')]

但是当我在linux下使用这些代码来解析命令行输出时,我得到了:

[('hex', '0x123456x00')]

它来自以下代码

 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,0x123456x00)"
>>> print s
(hex,0x123456)

用于容器内容(例如您在此处打印的元组的内容)的Python repr()函数确实显示了它:

>>> print repr(s)
'(hex,0x123456x00)'

正则表达式只是返回空字节,因为它存在于原始字符串中:

>>> import re
>>> s = "(hex,0x123456x00)"
>>> yourpattern = re.compile("((.*?),(.*?))")
>>> yourpattern.search(s).groups()
('hex', '0x123456x00')

如果要删除它,正则表达式引擎也不会返回它:

>>> yourpattern.search(s.replace('x00', '')).groups()
('hex', '0x123456')

在您的例子中,process.stdout迭代器产生的字符串包含空字节。

如果没有要删除的特定字符列表,strip将删除空白字符。这意味着制表符、换行符、垂直制表符、表单换行符、回车符和空格。

其中许多与大多数应用程序无关,但如果要删除null字符,则必须明确表示。例如,如果您想删除制表符、空格和null,那么您可以编写

line.strip('x00x09x20')

最新更新