删除最后括号中的所有内容

men*_*ith 2 java regex

我想删除所有括号,()如果(且仅当)它们位于末尾并且不匹配以下模式\(\d{4}\p{Pd}\d{4}\) *。该模式只不过是括号中的日期范围,例如。(1920-2988)

例如,我想匹配/捕获(用于删除,即string.replaceAll(my_regex_here, "")):

  • 富酒吧(blah)

  • foo bar(废话)废话(blah)

我不喜欢匹配:

  • 一些(废话)数据
  • 接下来的某个日期(1920-1921)。

我有以下正则表达式:\s*(.+?)\s*$。它往往会匹配太多:

  • 一些数据(..) match (match)
  • 一些数据(1920-1977)

InS*_*ync 5

使用负向预测来避免日期范围,然后使用以下命令实际匹配它[^()]+?

\s*\(                  # Match 0+ spaces, a '(',
(?!\d{4}\p{Pd}\d{4}\)) # which is not followed by a date range and a ')',
[^()]+                 # 1+ non-parenthesis characters and
\)\s*$                 # ')' then 0+ spaces right before the end of line.
Run Code Online (Sandbox Code Playgroud)

在 regex101.com 上尝试一下。

上面的正则表达式将不匹配:

parentheses with no content ()
years with more than 4 digits (1234-56789)
or less than 4 (123-4567)
nested ((brackets))
mismatched (brackets
Run Code Online (Sandbox Code Playgroud)