1

I have the following string:

String str = "{% assign foo = values %}.{{ foo[0] }}."

And I'm trying to compile it as a pattern with:

Pattern p = Pattern.compile(StringEscapeUtils.escapeJava(str));

but the compilation fails with the "Illegal repetition" error which I'm guessing is due to the '{' char not being escaped.

How can I escape it properly? Preferably without adding "\\" in front of every character.

Tudor
  • 61,523
  • 12
  • 102
  • 142
  • 1
    Related: http://stackoverflow.com/questions/60160/how-to-escape-text-for-regular-expression-in-java – Tomalak Dec 02 '11 at 17:22

3 Answers3

5

You do not want StringEscapeUtils.escapeJava() You want Pattern.quote().

Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Hmm, this would seem to be what I'm looking for, but it's also adding a \Q and \E at the beginning and end, respectively. – Tudor Dec 02 '11 at 17:13
  • @Tudor: That's all-right. [The docs](http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)) state *"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."*. – Tomalak Dec 02 '11 at 17:19
1

Escape with a \, in Java strings you have to escape the \ it self as well:

String str = "\\{% assign foo = values %\\}.\\{\\{ foo\\[0\\] \\}\\}\\.";

To escape meta characters automatically you can use Pattern.quote(str).

Qtax
  • 33,241
  • 9
  • 83
  • 121
0

Most PCRE engines, you can surround the literal text within the regex with \Q ... \E

where \Q is start qote of metachars, \E is end of quote metachars.

It essentially does a global find/replace of '([.*+?|()\[\]{}^\$\\])' with '\\$1' between the \Q and \E.