3

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

atomsfat
  • 2,863
  • 6
  • 34
  • 36

4 Answers4

7

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
  • 43,054
  • 9
  • 66
  • 56
6

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
  • 109,619
  • 77
  • 317
  • 330
1

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

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

chris
  • 9,745
  • 1
  • 27
  • 27
0

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

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