0

Possible Duplicate:
How to escape text for regular expression in Java

Is there a built in way or a standard library for cleaning arbitrary strings for use in regex?

As in, if I have the string something .* foo and I want to turn that into a regex like ^something \.\* foo$ is that something that can be easily done?

Community
  • 1
  • 1
Jeff
  • 12,555
  • 5
  • 33
  • 60

1 Answers1

4

You can use Pattern.quote(String) for this purpose. From the docs:

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.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181