【问题标题】:Creating Regex grouping of "OR" conditions to shorten an expression创建“OR”条件的正则表达式分组以缩短表达式
【发布时间】:2021-08-08 02:25:44
【问题描述】:

我正在捕获一个在文本消息中传递的字符串。该条件基于“联系人”一词。

以下是三个示例文本:

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

【问题讨论】:

    标签: python regex string regex-lookarounds string-matching


    【解决方案1】:

    你可以使用

    (?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']
    

    【讨论】:

      猜你喜欢
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      • 2013-12-23
      • 2010-09-16
      • 2020-01-09
      • 2015-12-03
      相关资源
      最近更新 更多