Java Regular Expression String.replaceAll

I want to replace the first context

web / style / clients.html

using java method String.replaceFirst so that I can get:

$ {pageContext.request.contextPath} /style/clients.html

I tried

String test =  "web/style/clients.html".replaceFirst("^.*?/", "hello/");

And it gives me:

hi / style / clients.html

but when i do

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

gives me

java.lang.IllegalArgumentException: link to an illegal group

+3
source share
4 answers

My guess is that it explodes, since $ is a special character. From the documentation

, () ($) , . , , .

, , -

"\\${pageContext.request.contextPath}/"
+7

Matcher.quoteReplacement():

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

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

. $

+1

$ , .

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

Source: https://habr.com/ru/post/1740358/


All Articles