Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression ^\\Q & \\E [duplicate]

Tags:

java

regex

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.

like image 941
learner Avatar asked Jun 11 '15 09:06

learner


People also ask

What is the meaning of \\ in regular expression?

Just like any other character, we escape it with a backslash: “\\” means match a backslash character.

What is the use of \\ in Java?

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.

What is the use of \\ s in string?

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.

What is the use of \n in regex?

"\n" matches a newline character.


3 Answers

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

like image 37
Mena Avatar answered Oct 01 '22 22:10

Mena


\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()), "");
like image 179
fge Avatar answered Oct 01 '22 21:10

fge


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.

like image 28
karthik manchala Avatar answered Oct 01 '22 22:10

karthik manchala