21

I have below code in my application:

private String getRequestPath(HttpServletRequest req) {
        String path = req.getRequestURI();
        path = path.replaceFirst( "^\\Q" + req.getContextPath() + "\\E", "");
        path = URLDecoder.decode(path);
        System.out.println("req.getRequestURI()="+req.getRequestURI());
        System.out.println("path="+path);
        return path;
    }

In the output I can see below messages when I try to access the servlet which this method belongs to:

req.getRequestURI()=/MyApp/test
path=/test

How the ^\\Q & \\E works in regular expressions.

1
  • You should not use them like that anyway. Use Pattern.quote instead - it's safer
    – nhahtdh
    Jun 11, 2015 at 9:43

3 Answers 3

32

\Q and \E are respectively the start and end of a literal string in a regex literal; they instruct the regex engine to not interpret the text inbetween those two "markers" as regexes.

For instance, in order to match two stars, you could have this in your regex:

\Q**\E

This will match two literal stars, and not try and interpret them as the "zero or more" quantifier.

Another, more portable solution of doing this instead of writing this by hand like in your code would be to use Pattern.quote:

path = path.replaceFirst(Pattern.quote(req.getContextPath()), "");
3

The \Q and \E delimiters are for quoting literals.

From the documentation:

\Q

Nothing, but quotes all characters until \E

\E

Nothing, but ends quoting started by \Q

1
  • The Javadoc for this is badly written. They introduce a new term - quoting - for something similar to escaping. And they don't explain what quoting is.
    – Dojo
    Jun 26 at 11:12
1

In a regular expression, all chars between the \Q and \E are escaped

So.. when you have a string to match and if it contains special regex characters you put the string inside \Q and \E to match them literally.

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