java 正则表达式 ^\\Q & \\E

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30776860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:38:41  来源:igfitidea点击:

Regular expression ^\\Q & \\E

javaregex

提问by learner

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:

在输出中,当我尝试访问此方法所属的 servlet 时,我可以看到以下消息:

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

How the ^\\Q& \\Eworks in regular expressions.

^\\Q&如何\\E在正则表达式中工作。

回答by fge

\Qand \Eare 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.

\Q\E分别是正则表达式文字中文字字符串的开始和结束;它们指示正则表达式引擎不要将这两个“标记”之间的文本解释为正则表达式。

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:

另一个更便携的解决方案是使用Pattern.quote

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

回答by Mena

The \Qand \Edelimiters are for quoting literals.

\Q\E分隔符是引用的文字。

From the documentation:

文档

\Q

\Q

Nothing, but quotes all characters until \E

什么都没有,但引用所有字符直到 \E

\E

\E

Nothing, but ends quoting started by \Q

什么都没有,但结束以 \Q 开头的引用

回答by karthik manchala

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

在正则表达式中,\Q 和 \E 之间的所有字符都被转义

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

所以..当你有一个要匹配的字符串并且它包含特殊的正则表达式字符时,你就把这个字符串放在里面\Q并按\E字面意思匹配它们。