【问题标题】:reference variable inside python regex matchpython 正则表达式匹配中的引用变量
【发布时间】:2016-03-14 08:47:24
【问题描述】:

我有一个简单的 python 脚本来解析日志文件,如果行匹配定义的模式,提取有问题的 IP 地址。

这是我的示例模式:

PATTERNS = [
'warning: Connection [a-zA-Z0-9_]+ limit exceeded: [0-9]+ from .*\[([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\] for service smtp',
'NOQUEUE: reject: RCPT from .*\[([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\]: .* Relay access denied; .*',
'NOQUEUE: reject: RCPT from .*\[([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\]: .* Recipient address rejected: User unknown in local recipient table; .*'
]

PATTERNS_COMPILED = re.compile("^(?:" + "|".join(PATTERNS) + ")")

问题是,行太长了。我想在外部定义 IP 匹配正则表达式并将其用作我的 PATTERN 匹配中的变量

如果我将 IP 定义为:

IP = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'

然后如何在我的 PATTERN 表达式中引用它? (我不想匹配字符串IP。我想匹配变量IP的值)

【问题讨论】:

  • 仅供参考:如果您需要完整的字符串匹配,则需要在模式末尾添加$。您只能声明IP 变量并使用它来定义PATTERNS 中的模式。 Python 不支持子模式递归(如 PCRE 中的\g<1>)。
  • 你说清楚了吗,或者你想要一个演示一下我的意思吗?
  • @Wiktor Stribiżew - 非常感谢。一个演示/示例会很棒。

标签: regex python-2.7


【解决方案1】:

您可以通过在匹配字符串中插入变量IP 来做到这一点:

IP = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'

PATTERNS = [                                  
'warning: Connection [a-zA-Z0-9_]+ limit exceeded: [0-9]+ from .*\[(' + IP + ')\] for service smtp',
'NOQUEUE: reject: RCPT from .*\[(' + IP + ')\]: .* Relay access denied; .*',
'NOQUEUE: reject: RCPT from .*\[(' + IP + ')\]: .* Recipient address rejected: User unknown in local recipient table; .*'
]

【讨论】:

    猜你喜欢
    • 2015-07-06
    • 1970-01-01
    • 2021-10-20
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    相关资源
    最近更新 更多