Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I always need to escape metacharacters in a string that is not a "literal"?

Tags:

java

string

regex

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

like image 336
Jim Avatar asked Oct 30 '15 20:10

Jim


2 Answers

Use Pattern.quote(String):

public static String quote(String s)

Returns a literal pattern String for the specified String.

This method produces a String that can be used to create a Pattern that would match the string s as 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

like image 156
John Kugelman Avatar answered Sep 21 '22 23:09

John Kugelman


You can use

java.util.regex.Pattern.quote(java.lang.String)

to escape meta characters used by regular expressions.

like image 33
Fabian Damken Avatar answered Sep 20 '22 23:09

Fabian Damken