2

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.)

4
  • Pattern.quote does 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)\E Commented Sep 6, 2017 at 22:38
  • It doesn't satisfy my particular use case. For example, as the next step, I want to do: text = text.replace(" ","\\s+"); Commented Sep 6, 2017 at 23:01
  • 1
    @BennettLynch You should put that into the question. But the answer may be that there's nothing that does what you want. Commented Sep 6, 2017 at 23:33
  • It might be sufficient to escape every metacharacter, with something like s.replaceAll("[\\\\[\\]{}().?+*^$]", "\\\\$0"). Commented Sep 7, 2017 at 2:06

1 Answer 1

2

Pattern.quote(String s) does exactly what you want.

Calling Pattern.quote("foo.bar(baz)") returns "\Qfoo.bar(baz)\E", which matches exactly the same as the pattern "foo\.bar\(baz\)".

Sign up to request clarification or add additional context in comments.

1 Comment

Pattern.quote won’t satisfy the requirement mentioned in Bennett’s comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.