【问题标题】:regex extract word group before the end of line正则表达式在行尾之前提取词组
【发布时间】:2021-05-06 22:57:50
【问题描述】:

我有以下字符串示例

commit: February 2021 Master DS Commit c285fcbf59b698ec5695d35989a420da7659
commit: March market Sales Volume PFJan2021
commit: August market Input PFJan2021
commit: February 2021 Master DS Commit c5695d359820da7659

我想提取介于commit: 和Commit c285cb... 或行尾之间的单词。结果如下:

February 2021 Master DS
March market Sales Volume PFJan2021
August market Input PFJan2021
February 2021 Master DS

我知道使用下面的正则表达式,我可以提取commit:之后的单词

.*commit: (.*)

我尝试了另一个正则表达式:.*commit: (.*)Commit.*,但它在Commit 字不存在的地方返回空白(我相信这是预期的行为)。

有没有办法使用某种样式的or 条件来检查Commit 单词是否存在返回commit: 之前和之后的单词?

【问题讨论】:

    标签: regex


    【解决方案1】:

    你可以使用

    commit:\s*(.*?)(?:\s*Commit\b|$)
    

    请参阅regex demo。

    详情:

    • commit: - 文字字符串
    • \s* - 零个或多个空格
    • (.*?) - 第 1 组:除换行符之外的任何零个或多个字符尽可能少
    • (?:\s*Commit\b|$) - 零个或多个空格,Commit 作为整个单词或字符串结尾。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-28
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多