It seems that having a string that contains the characters { or } is rejected during regex processing. I can understand that these are reserved characters and I need to escape them so if I do:
string.replaceAll("\\" + pattern);
This works, where pattern is any string starting with {.
Question: Is there a way to avoid such problems with strings that already contain such metachars so that it is handled automatically? Seems to me it should be the same as adding a double quote in a string literal vs accepting a string as input that already has the double quote
Use Pattern.quote(String):
public static String quote(String s)Returns a literal pattern
Stringfor the specifiedString.This method produces a
Stringthat can be used to create aPatternthat would match the stringsas if it were a literal pattern.Metacharacters or escape sequences in the input sequence will be given no special meaning.
Parameters:
s- The string to be literalized
Returns:
A literal string replacement
Since:
1.5
You can use
java.util.regex.Pattern.quote(java.lang.String)
to escape meta characters used by regular expressions.
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