【问题标题】:PCRE Regex: Exclude last portion of wordPCRE正则表达式:排除单词的最后一部分
【发布时间】:2021-09-08 20:43:53
【问题描述】:

我正在尝试在 PCRE 中编写一个正则表达式,它捕获单词的第一部分并排除第二部分。第一部分需要适应不同的值,具体取决于事务从何处发起。这是一个例子:

原始文本:

.controller.CustomerDemographicsController

已尝试正则表达式模式:

\.controller\.(?P<Controller>\w+)

尝试实现的结果粗体是我要保存在命名捕获组中的唯一内容):

.controller.CustomerDemographics控制器

注意:我尝试使用 ^、lookback 和 lookforward 排除。

非常感谢任何帮助。

【问题讨论】:

  • 停止的规则是什么?单词 char 序列中的最后一个大写字母?
  • @WiktorStribiżew,是的,这是停止的规则。
  • @WiktorStribiżew,成功了!非常感谢您的帮助。非常感谢!
  • 如果您只使用捕获组值,您实际上不必使用环视。如果是这种情况,this answer 也为您工作。

标签: regex regex-lookarounds


【解决方案1】:

您可以匹配 Controller 组中的单词字符直到最后一个大写字母:

\.controller\.(?P<Controller>\w+)(?=\p{Lu})

请参阅regex demo详情

  • \.controller\. - .controller\. 字符串
  • (?P&lt;Controller&gt;\w+) - 命名捕获组“控制器”:一个或多个单词字符尽可能多
  • (?=\p{Lu}) - 下一个字符必须是大写字母。

注意(?=\p{Lu}) 使\w+ 在最后一个大写字母之前停止,因为\w+ 模式由于+ 量词而变得贪婪。

【讨论】:

    【解决方案2】:

    另外,使用

    \.controller\.(?P<Controller>[A-Za-z]+)[A-Z]
    

    proof

    解释

    --------------------------------------------------------------------------------
      \.                       '.'
    --------------------------------------------------------------------------------
      controller               'controller'
    --------------------------------------------------------------------------------
      \.                       '.'
    --------------------------------------------------------------------------------
      (?P<Controller>           group and capture to Controller:
    --------------------------------------------------------------------------------
        [A-Za-z]+                any character of: 'A' to 'Z', 'a' to 'z'
                                 (1 or more times (matching the most
                                 amount possible))
    --------------------------------------------------------------------------------
      )                        end of Controller group
    --------------------------------------------------------------------------------
      [A-Z]                    any character of: 'A' to 'Z'
    

    【讨论】:

      猜你喜欢
      • 2016-05-09
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 2021-09-21
      • 2019-04-30
      • 1970-01-01
      • 2013-02-28
      • 2018-08-18
      相关资源
      最近更新 更多