我将一些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:
如您所见,我将regex复制粘贴到了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经常使用隐式布尔值。因此,在布尔上下文中,结果None
为False
您可以尝试使用,\s+
而不是仅仅\s
在开始时使用,看看是否可行。当我将测试字符串复制到编辑器时,我意外地使用两个前导空格(而不是一个空格)来复制它,当然该模式将不匹配,因为它仅检查一个空格。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句