Literalizing pattern strings
Whenever you need to literalize an arbitraryString
to be used as a regex pattern, use Pattern.quote
:
From the API:
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
This means that you can do the following:
String[] subDirs = path.split(Pattern.quote(File.separator));
Literalizing replacement strings
If you need to literalize an arbitrary replacement String
, use Matcher.quoteReplacement
.
From the API:
public static String quoteReplacement(String s)
Returns a literal replacement String
for the specified String
. This method produces a String
that will work as a literal replacement s
in the appendReplacement
method of the Matcher
class. The String
produced will match the sequence of characters in s
treated as a literal sequence. Slashes ('\'
) and dollar signs ('$'
) will be given no special meaning.
Parameters: s
- The string to be literalized
Returns: A literal string replacement
This quoted replacement String
is also useful in String.replaceFirst
and String.replaceAll
:
Note that backslashes (\
) and dollar signs ($
) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Use Matcher.quoteReplacement
to suppress the special meaning of these characters, if desired.
Examples
System.out.println(
"O.M.G.".replaceAll(".", "!")
); // prints "!!!!!!"
System.out.println(
"O.M.G.".replaceAll(Pattern.quote("."), "!")
); // prints "O!M!G!"
System.out.println(
"Microsoft software".replaceAll("so", "$0")
); // prints "Microsoft software"
System.out.println(
"Microsoft software".replaceAll("so", Matcher.quoteReplacement("$0"))
); // prints "Micro$0ft $0ftware"