Java - 正则表达式问题

Yat*_*oel 3 java regex

我想)通过正则表达式从字符串末尾删除字符.

例如,如果一个字符串是英国(英国),那么我想替换最后一个)符号.

注意:

1).正则表达式应该只删除最后一个)符号,无论)字符串中存在多少个符号.

Ben*_*n S 9

不要使用正则表达式来完成这个简单的任务.

// If the last ) might not be the last character of the String
String s = "Your String with) multiple).";
StringBuilder sb = new StringBuilder(s);
sb.deleteCharAt(s.lastIndexOf(')'));
s = sb.toString(); // s = "Your String with) multiple."

// If the last ) will always be the last character of the String
s = "Your String with))";
if (s.endsWith(")")) 
    s = s.substring(0, s.length() - 1);
// s = "Your String with)"
Run Code Online (Sandbox Code Playgroud)

  • @Anthony:确实,正则表达式解决方案永远不会像一个写得很好的非正则表达式解决方案那样高效,但这一点往往会被吹得太过分了.性能方面,正则表达式对于大多数应用程序来说已经足够了. (2认同)