我正在将一些 Perl 代码转换为 python,并且我有一个在 Perl 中完美运行的正则表达式,但当我将其复制到 re.match
时却不起作用。 Perl 行是:
if !(/(\s\{\s0x[0-9A-Fa-f]*, 0x[0-9A-Fa-f]*, .*\}.*)|(.* reservations for core .*)|(.* reservedMemoryAreas.*)/)
我对 python 的翻译是:
if re.match('(\s\{\s0x[0-9A-Fa-f]*, 0x[0-9A-Fa-f]*, .*\}.*)|(.* reservations for core .*)|(.* reservedMemoryAreas.*)',line)is None:
如您所见,我将正则表达式复制粘贴到 re
中,不包括封闭的 /
。然而,对于这一行,Perl 正则表达式匹配,但 python 正则表达式匹配:
{ 0x0000000097747E80, 0x40, 1, 0x0, 1, 0x0, 1, 0x0, 0, 0x0, 1, 0, "Res[0]" }, // Res[0]
正则表达式语法应该完全相同吗? 有人可以帮我从这里出去吗? 谢谢
最佳答案
我也使用你的模式在 Python 中得到了匹配。
import re
string = ' { 0x0000000097747E80, 0x40, 1, 0x0, 1, 0x0, 1, 0x0, 0, 0x0, 1, 0, "Res[0]" }, // Res[0]'
pattern = '(\s\{\s0x[0-9A-Fa-f]*, 0x[0-9A-Fa-f]*, .*\}.*)|(.* reservations for core .*)|(.* reservedMemoryAreas.*)'
if re.match(pattern, string):
print "Found match."
else:
print "No match."
>>> python test.py
>>> Found match.
另一件事:你不需要使用if ... is None:
,你可以只使用
if regex(pattern, string):
Python 大量使用隐式 bool 值。因此,在 bool 上下文中 None
的计算结果为 False
您可以尝试在开头使用 \s+
而不是仅使用 \s
,看看是否有效。当我将测试字符串复制到编辑器时,我不小心复制了两个前导空格而不是一个,这当然模式不会匹配,因为它只检查恰好一个。
关于python - 将 Perl 正则表达式转换为 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21019923/