简体   繁体   English

为什么这个正则表达式选择括号和之后虽然我使用前瞻

[英]Why this Regex selects parenthesis and after though I use look ahead

I use this regex我使用这个正则表达式

/\.(.+)?(?=(\(?)|\r\n)/gi

with

part1.part2
part1.part2(part3) part4

I want only match.part2 in both cases在这两种情况下我只想要 match.part2

but in second case I get.part2(part3) part4但在第二种情况下,我得到.part2(part3) part4

在此处输入图像描述

You should make the .+ part non-greedy, by using .+?您应该使用.+?使.+部分不贪婪。 , as otherwise it will also capture the opening parenthesis you want to see in the look-ahead part. ,否则它还将捕获您希望在前瞻部分中看到的左括号。

Also, in the second part, don't make the \( optional, otherwise you will be OK in having nothing in your look-ahead to match.此外,在第二部分中,不要将\(设为可选,否则您的前瞻中没有任何内容可以匹配。

Finally, don't match \r\n , but the end-of-line anchor $ in combination with the m flag (so that it matches the end of each line instead of the whole input).最后,不要匹配\r\n ,而是行尾锚$m标志的组合(以便它匹配每行的结尾而不是整个输入)。

So:所以:

\.(.+?)(?=\(|$)

regex101 link正则表达式101链接

You see the parenthesis in the match as the .您将匹配中的括号视为. can also match ( .也可以匹配( .

The pattern will match the rest of the line after the first dot without backtracking to a ( as the parenthesis in the lookahead is optional \(? and the assertion will be true.该模式将匹配第一个点之后的行的 rest 而不会回溯到(因为前瞻中的括号是可选的\(?并且断言将为真。

You could make use of a negated character class not crossing parenthesis or a newline when matching.您可以在匹配时使用不交叉括号或换行符的否定字符 class

\.([^()\r\n]+)

Regex demo正则表达式演示

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

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