创建 "OR" 条件的正则表达式分组以缩短表达式

Creating Regex grouping of "OR" conditions to shorten an expression

我正在捕获在短信中传递的字符串。条件是基于“接触”这个词。

以下是三个示例文本:

ntpd process is not running on lnx31 contact: app-support. @monitoringautomation
ntpd process is not running on lnx31 contact: app-support, @monitoringautomation
ntpd process is not running on lnx31 contact app-support @monitoringautomation

我当前的正则表达式是:

/(?i)contact:* (\S+),|(?i)contact:* (\S+)\.|(?i)contact:* (\S+)\s*/gm

我的问题是,是否有其他方法可以清理或缩短此表达式?我尝试了以下示例,但在使用句点或逗号时它不会捕获应用程序团队,而是将其包含在匹配项中。

/((?i)contact:* (\S+)(,|\.|\s*))/gm

您可以使用

(?i)\bcontact:*\s*([^,.\s]+)

参见regex demo

详情:

  • (?i) - 不区分大小写的内联修饰符选项
  • \b - 单词边界
  • contact - 字符串 contact
  • :* - 零个或多个冒号
  • \s* - 零个或多个空格
  • ([^,.\s]+) - 第 1 组:除空格、逗号和句点之外的一个或多个字符。

看到一个Python demo:

import re
text = """ntpd process is not running on lnx31 contact: app-support. @monitoringautomation
ntpd process is not running on lnx31 contact: app-support, @monitoringautomation
ntpd process is not running on lnx31 contact app-support @monitoringautomation"""
print( re.findall(r"(?i)\bcontact:*\s*([^,.\s]+)", text) )
# => ['app-support', 'app-support', 'app-support']