I want to replace the first context of
web/style/clients.html
with the java String.replaceFirst method so I can get:
${pageContext.request.contextPath}/style/clients.html
I tried
String test = "web/style/clients.html".replaceFirst("^.*?/", "hello/");
And this give me:
hello/style/clients.html
but when I do
String test = "web/style/clients.html".replaceFirst("^.*?/", "${pageContext.request.contextPath}/");
gives me
java.lang.IllegalArgumentException: Illegal group reference
4 Answers 4
My hunch is that it is blowing up as $ is a special character. From the documentation
Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.
So I believe you would need something like
"\\${pageContext.request.contextPath}/"
Comments
There is a method available already to escape all special characters in a replacement Matcher.quoteReplacement():
String test = "web/style/clients.html".replaceFirst("^.*?/", Matcher.quoteReplacement("${pageContext.request.contextPath}/"));
Comments
String test = "web/style/clients.html".replaceFirst("^.*?/", "\\${pageContext.request.contextPath}/");
should do the trick. $ is used for backreferencing in regexes
Comments
$ is a special character, you have to escape it.
String test = "web/style/clients.html".replaceFirst("^.*?/", "\\${pageContext.request.contextPath}/");