[英]why does replaceAll throw an exception
i have a string where i want to get rid of brackets 我有一个要删除括号的字符串
this is my string "(name)"
and i want to get "name"
这是我的字符串
"(name)"
,我想获取"name"
the same thing without the brackets 没有括号的同样的事情
i had String s = "(name)";
我有
String s = "(name)";
i wrote 我写
s = s.replaceAll("(","");
s = s.replaceAll(")","");
and i get an exception for that 我对此有一个例外
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 1
(
how do i get rid of the brackets? 我如何摆脱括号?
Parenthesis characters (
and )
delimit the bounds of a capturing group in a regular expression which is used as the first argument in replaceAll
. 括号字符
(
和)
在正则表达式中界定捕获组的边界,该正则表达式用作replaceAll
的第一个参数。 The characters need to be escaped. 字符需要转义。
s = s.replaceAll("\\(","");
s = s.replaceAll("\\)","");
Better yet, you could simply place the parenthesis in a character class to prevent the characters being interpreted as meta-characters 更好的是,您可以简单地将括号放在字符类中,以防止将字符解释为元字符
s = s.replaceAll("[()]","");
s = s.replace("(", "").replace(")", "");
Regex isn't needed here. 这里不需要正则表达式。
If you wanted to use Regex (not sure why you would) you could do something like this: 如果您想使用正则表达式(不确定为什么),可以执行以下操作:
s = s.replaceAll("\\\\(", "").replaceAll("\\\\)", "");
The problem was that (
and )
are meta characters so you need to escape them (assuming you want them to be interpreted as how they appear). 问题是
(
和)
是元字符,因此您需要对其进行转义(假设您希望将它们解释为它们的外观)。
String#replaceAll takes regular expression as argument. String#replaceAll将正则表达式作为参数。 You are using
Grouping Meta-characters
as regular expression argument.That is why getting error. 您正在使用将
Grouping Meta-characters
作为正则表达式参数,这就是为什么会出错的原因。
Meta-characters are used to group, divide, and perform special operations in patterns.
元字符用于按模式分组,划分和执行特殊操作。
\ 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
So use 所以用
1. \\\\(
instead of (
1.
\\\\(
代替(
2. \\\\)
instead of )
2.
\\\\)
代替)
You'll need to escape the brackets like this: 您需要像这样逃避括号:
s = s.replaceAll("\\(","");
s = s.replaceAll("\\)","");
You need two slashes since the regex processing engine would need to see a \\(
to process the bracket as a literal bracket (and not as part of the regex expression), and you'll need to escape the backslash so the regex engine would be able to see it as a backslash. 您需要两个斜杠,因为正则表达式处理引擎需要看到一个
\\(
才能将括号作为文字括号处理(而不是作为正则表达式的一部分),并且您需要转义反斜杠,因此正则表达式引擎将能够将其视为反斜线。
You need to escape the ( and the ) they have special string literal meaning. 您需要转义(和)它们具有特殊的字符串文字含义。 Do it like this:
像这样做:
s = s.replaceAll("\\(","");
s = s.replaceAll("\\)","");
s=s.replace("(","").replace(")","");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.