Lena Bru
Lena Bru

Reputation: 13947

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"

the same thing without the brackets

i had 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?

Upvotes: 1

Views: 6084

Answers (6)

Prabhaker A
Prabhaker A

Reputation: 8473

String#replaceAll takes regular expression as argument. You are using Grouping Meta-characters as regular expression argument.That is why getting error.

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 (
2. \\) instead of )

Upvotes: 3

Ahmed Adel Ismail
Ahmed Adel Ismail

Reputation: 2184

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

Upvotes: 1

Reimeus
Reimeus

Reputation: 159844

Parenthesis characters ( and ) delimit the bounds of a capturing group in a regular expression which is used as the first argument in 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("[()]","");

Upvotes: 8

Dhruv Kapoor
Dhruv Kapoor

Reputation: 1081

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.

Upvotes: 2

tom
tom

Reputation: 354

You need to escape the ( and the ) they have special string literal meaning. Do it like this:

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

Upvotes: 1

Josh M
Josh M

Reputation: 11947

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

Upvotes: 4

Related Questions