Java String.replaceAll正则表达式

ato*_*fat 3 java regex replace

我想替换第一个上下文

网络/风格/ clients.html

使用java String.replaceFirst方法,我可以得到:

$ {} pageContext.request.contextPath /style/clients.html

我试过了

String test =  "web/style/clients.html".replaceFirst("^.*?/", "hello/");
Run Code Online (Sandbox Code Playgroud)

这给了我:

你好/风格/ clients.html

但是当我这样做的时候

 String test =  "web/style/clients.html".replaceFirst("^.*?/", "${pageContext.request.contextPath}/");
Run Code Online (Sandbox Code Playgroud)

给我

java.lang.IllegalArgumentException:非法组引用

Rob*_*rco 7

我的预感是它正在爆炸,因为$是一个特殊的角色.从文档中

请注意,替换字符串中的反斜杠()和美元符号($)可能会导致结果与将其视为文字替换字符串时的结果不同.如上所述,美元符号可被视为对捕获的子序列的引用,反斜杠用于替换替换字符串中的文字字符.

所以我相信你会需要类似的东西

"\\${pageContext.request.contextPath}/"
Run Code Online (Sandbox Code Playgroud)


ser*_*erg 6

有一种方法可用于转义替换中的所有特殊字符Matcher.quoteReplacement():

String test =  "web/style/clients.html".replaceFirst("^.*?/", Matcher.quoteReplacement("${pageContext.request.contextPath}/"));
Run Code Online (Sandbox Code Playgroud)