正则表达式-避免括号的匹配句子

时间:2018-08-02 16:17:15

标签: regex keyword parentheses sentence

我需要做一个正则表达式来匹配大文本中的关键字。

大文本示例如下:

  

...另一句结尾关键字:标签1,标签2,标签3(可能包含   像这样的参考。 1),标签4和标签5。   已经开始...

正则表达式必须提取:

  

关键字:标记1,标记2,标记3(可能包含   像这样的参考。 1),标签4和标签5

我有以下代码:

\bKeywords:[^\.]+

但是问题是正则表达式不能避免括号内的文本,而是以“ ..ref。1 ..”上的点结尾。

谢谢大家!

注意:“标签”一词只是一个例子,可以是任何单词。

1 个答案:

答案 0 :(得分:1)

假设无法嵌套括号:Keywords: (?:[^(.]|\([^)]*\))*

我要匹配:

(?:[^(.]|\([^)]*\))*
                   * as many times as possible
(?:               )  non-capturing
        |            either:
   [^(.]             a character that's not an opening paranthesis or a dot, or
         \(     \)   inside literal parantheses
           [^)]*     as many characters that aren't closing parantheses as possible

如果可以嵌套括号 ,则正则表达式不是您想要的,因为您尝试捕获的语言是context-free