【问题标题】:regular expression match _ underscore正则表达式匹配_下划线
【发布时间】:2015-03-29 13:13:51
【问题描述】:

我有一个这样的字符串:

002_part1_part2_______________by_test

我想在第二个下划线字符处停止匹配,像这样:

002_part1_part2_

如何使用正则表达式做到这一点?

谢谢

【问题讨论】:

    标签: regex pattern-matching match


    【解决方案1】:

    创建一个模式来匹配任何字符,但不匹配_ 零次或多次后跟下划线符号。将该模式放入捕获或非捕获组中,并通过在该组旁边添加范围量词 {3} 使其精确重复 3 次。

    ^(?:[^_]*_){3}
    

    DEMO

    【讨论】:

      【解决方案2】:

      你可以使用:

      .*\d_
      

      解释:

      Match any single character that is NOT a line break character (line feed) «.*»
         Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
      Match a single character that is a “digit” (any decimal number in any Unicode script) «\d»
      Match the character “_” literally «_»
      

      https://regex101.com/r/uX0qD5/1

      【讨论】:

      • 这个互动教程非常适合学习正则表达式:regexone.com
      • @GabryRome 您使用哪种语言?
      • 如果我想在 shell 脚本中使用您的正则表达式,我该怎么办?
      • 在 shell 脚本中我以这种方式更改了它:echo expr "$string" : '\(.*[0-9]_\)' 并且工作得很好! :-) 非常感谢
      • 只有一件事@PadreoLobito 如果我有这样的字符串怎么办:002_Digital_test_______________by_test ??????谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      相关资源
      最近更新 更多