0

I have a question about using replaceAll() function.

if a string has parentheses as a pair, replace it with "",

while(S.contains("()"))
        {
            S = S.replaceAll("\\(\\)", "");
        }

but why in replaceAll("\\(\\)", "");need to use \\(\\)?

6 Answers 6

2

Because as noted by the javadocs, the argument is a regular expression.

Parenthesis in a regular expression are used for grouping. If you're going to match parenthesis as part of a regular expression they must be escaped.

Sign up to request clarification or add additional context in comments.

Comments

1

It's because replaceAll expects a regex and ( and ) have a special meaning in a regex expressions and need to be escaped.

An alternative is to use replace, which counter-intuitively does the same thing as replaceAll but takes a string as an input instead of a regex:

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

1 Comment

@xagyg WRONG! You seem to forget that String implements CharSequence.
1

First, your code can be replaced with:

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

without the while loop.

Second, the first argument to .replaceAll() is a regular expression, and parens are special tokens in regular expressions (they are grouping operators).

And also, .replaceAll() replaces all occurrences, so you didn't even need the while loop here. Starting with Java 6 you could also have written:

S = S.replaceAll("\\Q()\\E", "");

It is let as an exercise to the reader as to what \Q and \E are: http://regularexpressions.info gives the answer ;)

1 Comment

Erm, wrong: docs.oracle.com/javase/7/docs/api/java/lang/… -- this method has two overloads
1

S = S.replaceAll("\(\)", "") = the argument is a regular expression.

Comments

0

Because the method's first argument is a regex expression, and () are special characters in regex, so you need to escape them.

Comments

0

Because parentheses are special characters in regexps, so you need to escape them. To get a literal \ in a string in Java you need to escape it like so : \\.

So () => \(\) => \\(\\)

2 Comments

but why need to escape twice?
@ratzip Normally regex needs one \ to escape special meaning of meta-character, but in String \ is also special character (you use it to escape special meaning of some characters like quotes \", or to make special characters like new line \n). So to pass \ char to regex engine you first need to escape its special meaning in String with another \ before it.