More precisely: Do
Pattern.compile(s, x | Pattern.LITERAL)
and
Pattern.compile(Pattern.quote(s), x)
create equivalent regexes for any String s
and any other flag x
?
If not, how to simulate Pattern.LITERAL?
Short answer: For your example, yes.
Long answer: Yes, but Pattern.quote is more flexible. What if you only wanted some of your pattern quoted? Like:
Pattern.compile(Pattern.quote(s) + "+", x)
With setting the Pattern.LITERAL flag, even the +
character would now be treated literally.
If you don't trust the documentation, maybe looking at the source code at Google Code Search for Pattern.compile
will help.
From what I can derive from looking at the source code:
If the LITERAL flag is not set, regardless of all the other flags, it will look for any \Q...\E quoted blocks and manually escape special characters, just as one would expect.
If the LITERAL flag is set, it will convert the whole pattern using the newSlice method, and there are special cases for at least the
CASE_INSENSITIVE
flag andUNICODE_CASE
flag
Given the question as is, the answer is no, because of setting x=Pattern.LITERAL leading to quoting s
twice in the second expression. With double quoting and s="A"
the String "A"
won't be matched, but the String "\\QA\\E"
will. However,
Pattern.compile(s, x | Pattern.LITERAL)
seem to be equivalent to
Pattern.compile(Pattern.quote(s), x & ~Pattern.LITERAL)
Although I do not see a problem with it, I don’t quite trust applying arbitrary pattern flags together with whole-pattern quoted stuff. The documentation mentions that it renders all flags but two superfluous, after all. I think it would be ok, but color me méfiant — mistrusting.
Have you tried using \Q … \E
on just those parts of the pattern that you wish quoted into non–meta‐ness, so to speak?
精彩评论