Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String ReplaceAll method giving illegal repetition error?

I have a string and when I try to run the replaceAll method, I am getting this strange error:

String str = "something { } , op"; str = str.replaceAll("o", "\n"); // it works fine str = str.replaceAll("{", "\n"); // does not work 

and i get a strange error:

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition {   

How can I replace the occurrences of "{" ?

like image 945
Johnydep Avatar asked Dec 13 '11 14:12

Johnydep


People also ask

Does replaceAll replace original string?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

What does in replaceAll () mean in Java?

Java String replaceAll() The replaceAll() method replaces each substring that matches the regex of the string with the specified text.

What does the replaceAll () method on list do?

replaceAll() - Replaces all elements of the arraylist into uppercase.


1 Answers

A { is a regex meta-character used for range repetitions as {min,max}. To match a literal { you need to escape it by preceding it with a \\:

str = str.replaceAll("\\{", "\n"); // does work 
like image 160
codaddict Avatar answered Sep 25 '22 13:09

codaddict