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.
Just like any other character, we escape it with a backslash: “\\” means match a backslash character.
The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.
The string \s is a regular expression that means "whitespace", and you have to write it with two backslash characters ( "\\s" ) when writing it as a string in Java.
"\n" matches a newline character.
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
\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()), "");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With