Java - 正则表达式问题

标签 java regex

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

例如,如果一个字符串是 UK(Great Britain),那么我想替换最后一个 ) 符号。

注意:

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

最佳答案

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

// 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)"

关于Java - 正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2646773/

相关文章:

javascript - 如何迭代 JSON 列表?

java - 我应该增加依赖项更新的主要版本吗

java - 在 java 中序列化 Float 以供 C++ 应用程序读取的最佳方法?

java - org.apache.catalina.LifecycleException : Failed to start component [StandardEngine[Catalina]. StandardHost[本地主机].StandardContext

javascript - 如何使用 javascript 将给定字符串更改为正则表达式修改的字符串

java - Java HashSet.isEmpty() 中的 NPE

.net - 原子量化组与量化原子组的含义相同吗?

javascript - 尝试使用正则表达式来匹配范围

java - 如何使用 RegExp 将一个字符串替换为另一个字符串,并且替换的字符串将包含第一个字符串的参数

Javascript 正则表达式和日语符号