Does Pattern.LITERAL use the same as Pattern.quote?

More precisely: Do

Pattern.compile(s, x | Pattern.LITERAL) 

and

 Pattern.compile(Pattern.quote(s), x) 

create equivalent regular expressions for any string s and any other flag x ?

If not, how do you simulate Pattern.LITERAL?

+6
java regex
source share
3 answers

Given the question as is, the answer is no, due to the setting x = Pattern.LITERAL leads to quoting s twice in the second expression. When double quoted and s="A" string "A" will not be matched, but String "\\QA\\E" will be. Nevertheless,

 Pattern.compile(s, x | Pattern.LITERAL) 

seems equivalent

 Pattern.compile(Pattern.quote(s), x & ~Pattern.LITERAL) 
+1
source share

Short answer: for your example, yes.

Long answer: Yes, but Pattern.quote is more flexible. What if you want some of your templates to be quoted? How:

 Pattern.compile(Pattern.quote(s) + "+", x) 

When the Pattern.LITERAL flag is set, even the + symbol will now be processed literally.

If you don't trust the documentation, maybe check out the source code on Google Code Search for Pattern.compile .

From which I can get the source code:

  • If the LITERAL flag is not set, regardless of all other flags, it will look for any quotes \ Q ... \ E and manually launch special characters, just as you would expect.

  • If the LITERAL flag is set, it will convert the entire template using the newSlice method, and there are special cases for the smallest CASE_INSENSITIVE flag and the UNICODE_CASE flag

+3
source share

Although I do not see a problem with this, I do not trust the use of arbitrary template flags along with whole quotes. the documentation mentions that in any case it displays all the flags, but two extra ones. I think that everything will be fine, but the color will not be me - distrust.

Have you tried to use \Q … \E only those parts of the pattern that you want to quote, not to mention this?

0
source share

All Articles