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 "{"
?
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.
Java String replaceAll() The replaceAll() method replaces each substring that matches the regex of the string with the specified text.
replaceAll() - Replaces all elements of the arraylist into uppercase.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With