正则表达式匹配_下划线

时间:2015-03-29 13:13:51

标签: regex pattern-matching match

我有一个这样的字符串:

002_part1_part2 _______________ by_test

我希望在第二个下划线字符处停止匹配,如下所示:

002_part1_part2 _

如何使用正则表达式执行此操作?

由于

2 个答案:

答案 0 :(得分:1)

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

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

DEMO

答案 1 :(得分:0)

您可以使用:

.*\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