views:

61

answers:

4

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

+5  A: 

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}/"
Rob Di Marco
+1  A: 

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

should do the trick. $ is used for backreferencing in regexes

oedo
A: 

$ is a special character, you have to escape it.

String test =  "web/style/clients.html".replaceFirst("^.*?/", "\\${pageContext.request.contextPath}/");
Kylar
+2  A: 

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}/"));
serg