Java String.replaceAll正则表达式
我想替换第一个上下文
网络/风格/ clients.html
使用java String.replaceFirst方法,我可以得到:
$ {} pageContext.request.contextPath /style/clients.html
我试过了
String test = "web/style/clients.html".replaceFirst("^.*?/", "hello/");
这给了我:
你好/风格/ clients.html
但是当我这样做的时候
String test = "web/style/clients.html".replaceFirst("^.*?/", "${pageContext.request.contextPath}/");
给我
java.lang.IllegalArgumentException:非法组引用
我的预感是它正在爆炸,因为$是一个特殊的角色。 从文档中
请注意,替换字符串中的反斜杠()和美元符号($)可能会导致结果与将其视为文字替换字符串时的结果不同。 如上所述,美元符号可被视为对捕获的子序列的引用,反斜杠用于替换替换字符串中的文字字符。
所以我相信你需要类似的东西
"\\${pageContext.request.contextPath}/"
有一种方法可用于转义替换Matcher.quoteReplacement()
中的所有特殊字符:
String test = "web/style/clients.html".replaceFirst("^.*?/", Matcher.quoteReplacement("${pageContext.request.contextPath}/"));
String test = "web/style/clients.html".replaceFirst("^.*?/", "\\${pageContext.request.contextPath}/");
应该做的伎俩。 $用于正则表达式中的反向引用
$是一个特殊的角色,你必须逃脱它。
String test = "web/style/clients.html".replaceFirst("^.*?/", "\\${pageContext.request.contextPath}/");