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

asked Apr 8, 2010 at 17:35

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}/"
answered Apr 8, 2010 at 17:39
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}/"));
answered Apr 8, 2010 at 18:28

Comments

1

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

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

answered Apr 8, 2010 at 17:40

Comments

0

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

String test = "web/style/clients.html".replaceFirst("^.*?/", "\\${pageContext.request.contextPath}/");
answered Apr 8, 2010 at 17:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.