user707549
user707549

Reputation:

how to replace a string in Java

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 \\(\\)?

Upvotes: 0

Views: 2030

Answers (6)

Ridzuan Adris
Ridzuan Adris

Reputation: 1272

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

Upvotes: 1

Marcos
Marcos

Reputation: 4653

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 () => \(\) => \\(\\)

Upvotes: 0

asgoth
asgoth

Reputation: 35829

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

Upvotes: 0

fge
fge

Reputation: 121820

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 ;)

Upvotes: 1

assylias
assylias

Reputation: 328855

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("()", "");

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76918

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.

Upvotes: 2

Related Questions