在正则表达式中动态跳过部分

Skipping sections dynamically in a regular expression

我正在尝试开发一个正则表达式来匹配句子中的第一个句点 - 只要该句点不在任何括号内。

因此,例如,字符串:

Tom (Ed.) went down to the shop where the owners (J. Guys, A. Owner, and B. Ains) gathered. It was a great night.

应该return:

Tom (Ed.) went down to the shop where the owners (J. Guys, A. Owner, and B. Ains) gathered.

但是,我发现使用懒惰的方法,我只能得到:

Tom (Ed.

并且,使用贪婪的方法,显然我得到了整个句子。并不是所有的句子都是这样构造的(比如有些句子没有括号),我也尝试过使用否定查找,但我不是特别理解。

有人知道如何进行吗?

您可以在 Java 中使用此正则表达式来匹配不在圆括号内的句点:

(?=([^(]*\([^)]*")*[^)]*$)\.

要匹配整个 Tom (Ed.) went down to the shop where the owners (J. Guys, A. Owner, and B. Ains) gathered. 句子,您可以使用

.*?(?=([^(]*\([^)]*")*[^)]*$)\.

看看demo。此外,在 Java 中,您必须对斜杠进行两次转义:

 String pattern = ".*?(?=([^(]*\([^)]*")*[^)]*$)\.";

您可以使用以下内容:

[^().]*\([^)]*\)[^().]*

Demo

此模式包含 3 个部分:

2 部分 [^().]* 将匹配除 () 和点

之外的任何字符串的任何长度

\([^)]*\) 将括号与内容匹配。