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;
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
How the ^\\Q & \\E works in regular expressions.
\Q和\E分别是正则表达式文字中文字字符串的开始和结尾;他们指示正则表达式引擎不要将这两个“标记”之间的文本解释为正则表达式。
例如,为了匹配两颗星,可以在正则表达式中包含以下内容:
\Q**\E
Run Code Online (Sandbox Code Playgroud)
这将匹配两个文字恒星,而不是尝试将它们解释为“零个或多个”量词。
这样做而不是像在代码中那样手动编写的另一种更可移植的解决方案是使用Pattern.quote:
path = path.replaceFirst(Pattern.quote(req.getContextPath()), "");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8564 次 |
| 最近记录: |