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

4 Answers 4

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}/"
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.