【问题标题】:How can I ignore empty groups?如何忽略空组?
【发布时间】:2022-11-16 04:48:32
【问题描述】:

非常简单的正则表达式,我正在尝试从日志中提取 IP。但是 group(1) 是空的,这是给定的。有没有更好的方法来解决这个问题?

sourceip_regex_extract = re.compile(r"{}".format(sourceip_syslog_regex))
sourceip_extract = sourceip_regex_extract.search(message) 
sourceip_txt = sourceip_extract.group(1)

Regex101:https://regex101.com/r/jmtQci/1

【问题讨论】:

  • 参见regex101.com/r/jmtQci/2\b(?:from |inside:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})
  • 你能分解这个吗?加上 regex101 说“您的正则表达式与主题字符串不匹配。”
  • 我添加了\b,删除它

标签: python regex


【解决方案1】:

首先,当您使用正则表达式搜索匹配项时,请确保您确实获得了匹配项,然后才访问第一个组值。

接下来,r"{}".format(sourceip_syslog_regex)就没有意义了,它和sourceip_syslog_regex是一样的。

要解决当前问题,您可以使用 (?:from |inside:) 交替匹配 from inside:

sourceip_syslog_regex = r'(?:from |inside:)(d{1,3}.d{1,3}.d{1,3}.d{1,3})'
sourceip_regex_extract = re.compile(sourceip_syslog_regex)
sourceip_extract = sourceip_regex_extract.search(message) 
if sourceip_extract:
    sourceip_txt = sourceip_extract.group(1)

regex demo

请注意,您可以稍微缩短 IP 地址匹配模式并使用 (?:from |inside:)(d{1,3}(?:.d{1,3}){3})

细节

  • (?:from |inside:) - from inside:
  • (d{1,3}(?:.d{1,3}){3}) - 第 1 组:一到三位数字,然后出现三次 . 和一到三位数字。

【讨论】:

  • 啊!好吧,实际上那是变量。但是,是的,你是对的,谢谢你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
  • 2021-12-31
  • 2011-02-05
相关资源
最近更新 更多