1

我有输入文本,例如:

Text (Some Other Text) (More Text)

我要做的是完全删除最后一个括号以及其中的文本。IE(More Text)
更一般地说,我希望表达式只匹配最后一个括号和内容。

我已经测试了以下正则表达式的很多变体,\s\(.*?\)$但我似乎无法让它工作,我可以说 . 运算符一直匹配第一个括号,直到最后一个右括号,但是无论我尝试过什么,我似乎都想不出如何解决这个问题。

我正在使用正则表达式的 Java 实现。(省略上面多余的转义字符)

4

4 回答 4

3
public static void main(String[] args){ 
        String reg = "\\s\\([^)]+\\)$";
        String text = "Text (Some Other Text) (More Text)";
        System.out.println(text.replaceAll(reg, ""));
}

输出 :

Text (Some Other Text)

编辑: 如果您在最后一个括号后有一些额外的文字,@anubhava 提供了一个很好的解决方案

于 2013-05-15T15:35:06.197 回答
1

以下应该为您工作:

String regex = "\\s+\\([^)]+\\)([^()]*)$";
String text  = "Text (Some Other Text) (More Text) foo";
String repl  = text.replaceAll(regex, "$1");    
// Text (Some Other Text) foo

现场演示:http: //ideone.com/WnUeIQ

或使用正向前瞻

String regex = "\\s+\\([^)]+\\)(?=[^()]*$)";
String text  = "Text (Some Other Text) (More Text) foo";
String repl  = text.replaceAll(regex, "");

现场演示:http: //ideone.com/2HRBf0

于 2013-05-15T15:52:36.780 回答
0

试试这个

    String s = "Text (Some Other Text) (More Text)";
    s = s.replaceAll(".*\\((.+)\\)$", "$1");
    System.out.println(s);

输出

More Text
于 2013-05-15T15:34:36.897 回答
0

如果您的文本始终采用该格式,则不需要正则表达式,它效率低下。

这很好,并且会比正则表达式更快:

String s = "Text (Some Other Text) (More Text)";
s = s.substring(0,s.lastIndexOf('('));
System.out.println(s);
于 2013-05-15T15:39:44.387 回答