简体   繁体   English

如何形成正则表达式以匹配所有内容到“(”

[英]How to form regex to match everything up to a "("

In javascript, how can a regular expression be formed to match everything up to and NOT including an opening parenthesis "("?在 javascript 中,如何形成正则表达式以匹配所有内容,但不包括左括号“(”?

example input:示例输入:

"12(pm):00" "12(am):))" "8(am):00" "12(pm):00" "12(am):))" "8(am):00"

ive found /^(.*?)\\(/ to be successful with the "up to" part, but the match returned includes the "("我发现/^(.*?)\\(/在“高达”部分成功,但返回的匹配包括“(”

In regex101.com, its says the first capturing group is what im looking for, is there a way to return only the captured group?在 regex101.com 中,它说第一个捕获组是我要找的,有没有办法只返回捕获的组?

There are three ways to deal with this.有三种方法可以解决这个问题。 The first is to restrict the characters you match to not include the parenthesis:第一个是限制你匹配的字符不包括括号:

 let match = "12(pm):00".match(/[^(]*/); console.log(match[0]);

The second is to only get the part of the match you are interested in, using capture groups:第二种是使用捕获组仅获取您感兴趣的匹配部分:

 let match = "12(pm):00".match(/(.*?)\\(/); console.log(match[1]);

The third is to use lookahead to explicitly exclude the parenthesis from the match:第三种是使用lookahead从匹配中明确排除括号:

 let match = "12(pm):00".match(/.*?(?=\\()/); console.log(match[0]);

As in OP, note the non-greedy modifier in the second and third case: it is necessary to restrict the quantifier in case there is another open parenthesis further inside the string.与 OP 一样,请注意第二种和第三种情况下的非贪婪修饰符:有必要限制量词,以防字符串内部还有另一个开括号。 This is not necessary in the first place, since the quantifier is explicitly forbidden to gobble up the parenthesis.这首先不是必需的,因为明确禁止量词吞噬括号。

Try尝试

^\d+

^ asserts position at start of a line ^在行首断言位置

\\d matches a digit (equal to [0-9]) \\d匹配一个数字(等于 [0-9])

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) +量词——匹配一次和无限次,尽可能多次,根据需要回馈(贪婪)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM