python - 将 Perl 正则表达式转换为 python

标签 python regex perl

我正在将一些 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/

相关文章:

python - 在 Python 中使用 Paramiko 连接到端口 443 时出现 "Error reading SSH protocol banner"

python - 查找以特定符号开头,然后连续出现特定单词和模式的多个匹配项

arrays - 是否可以在 Perl foreach 循环中分配两个变量?

regex - 使用 perl 的多个正则表达式

Python默认比较表示的魔术方法?

Python Eventlet 产卵不起作用

Python selenium - 如何重复选择多个页面上的按钮 - 元素不可见

regex - 追加到 eclipse 的行尾

jquery - Javascript,从每个循环中获取唯一值或按 value.id 进行分组

perl - 适合初学者的小型可运行 www::Mechanize 示例