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?

0

1 Answer 1

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.

1
  • Great, thank you. I'll accept your answer when I am able to.
    – Jeff
    Mar 27, 2012 at 3:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.