I'm looking for a utility method in Java that will escape all regex metacharacters in a given String.
I want to convert this:
foo.bar(baz)
Into this:
foo\.bar\(baz\)
So that I can take any sample string and convert it into a regex-friendly search pattern. Surely one must exist, but I cannot seem to find anything.
(Pattern.quote(String s) offers something similar to what I need, but not the exact same functionality.)
Pattern.quotedoes do what you want ("take any sample string and convert it into a regex-friendly search pattern") though it escapes the entire string as a whole rather than individually quoting individual meta-characters in the string.foo.bar(baz)then becomes\Qfoo.bar(baz)\Etext = text.replace(" ","\\s+");s.replaceAll("[\\\\[\\]{}().?+*^$]", "\\\\$0").