繁体   English   中英

为什么replaceAll引发异常

[英]why does replaceAll throw an exception

我有一个要删除括号的字符串

这是我的字符串"(name)" ,我想获取"name"

没有括号的同样的事情

我有String s = "(name)";

我写

s = s.replaceAll("(","");
s = s.replaceAll(")","");

我对此有一个例外

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 1
(

我如何摆脱括号?

括号字符()在正则表达式中界定捕获组的边界,该正则表达式用作replaceAll的第一个参数。 字符需要转义。

s = s.replaceAll("\\(","");
s = s.replaceAll("\\)","");

更好的是,您可以简单地将括号放在字符类中,以防止将字符解释为元字符

s = s.replaceAll("[()]","");

s = s.replace("(", "").replace(")", "");

这里不需要正则表达式。

如果您想使用正则表达式(不确定为什么),可以执行以下操作:

s = s.replaceAll("\\\\(", "").replaceAll("\\\\)", "");

问题是()是元字符,因此您需要对其进行转义(假设您希望将它们解释为它们的外观)。

String#replaceAll将正则表达式作为参数。 您正在使用将Grouping Meta-characters作为正则表达式参数,这就是为什么会出错的原因。

元字符用于按模式分组,划分和执行特殊操作。

\       Escape the next meta-character (it becomes a normal/literal character)
^       Match the beginning of the line
.       Match any character (except newline)
$       Match the end of the line (or before newline at the end)
|       Alternation (‘or’ statement)
()      Grouping
[]      Custom character class

所以用
1. \\\\(代替(
2. \\\\)代替)

您需要像这样逃避括号:

s = s.replaceAll("\\(","");
s = s.replaceAll("\\)","");

您需要两个斜杠,因为正则表达式处理引擎需要看到一个\\(才能将括号作为文字括号处理(而不是作为正则表达式的一部分),并且您需要转义反斜杠,因此正则表达式引擎将能够将其视为反斜线。

您需要转义(和)它们具有特殊的字符串文字含义。 像这样做:

s = s.replaceAll("\\(","");
s = s.replaceAll("\\)","");
s=s.replace("(","").replace(")","");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM