使用replace first方法替换字符串

时间:2022-06-12 16:51:31

I was trying to use the string replace with another, it doesn't happen.

我试图使用字符串替换另一个,它不会发生。

String requestURI = "/webapps-ab/public/Test.jsp"
String contextName = "webapps-ab";
String newRequestURI = requestURI.replaceFirst(contextName,"webapps");

I am expecting newRequestURI to be "/webapps/public/Test.jsp".

我期待newRequestURI成为“/webapps/public/Test.jsp”。

2 个解决方案

#1


3  

Your replace call should be:

你的替换电话应该是:

String newRequestURI = requestURI.replaceFirst(contextName, "webapps");

Using:

使用:

String requestURI = "/webapps-ab/public/Test.jsp";
String contextName = "webapps-ab";
String newRequestURI = requestURI.replaceFirst(contextName, "webapps");
System.out.println("newRequestURI: " + newRequestURI);

The output will be what you're expecting:

输出将是您所期望的:

newRequestURI: /webapps/public/Test.jsp

ideone example.

一个例子。

#2


0  

When referencing a variable, do not surround it in quotes, as that converts it into a literal String object.

引用变量时,不要用引号括起来,因为它将它转换为文字String对象。

String newRequestURI = requestURI.replaceFirst(contextName, "webapps");

#1


3  

Your replace call should be:

你的替换电话应该是:

String newRequestURI = requestURI.replaceFirst(contextName, "webapps");

Using:

使用:

String requestURI = "/webapps-ab/public/Test.jsp";
String contextName = "webapps-ab";
String newRequestURI = requestURI.replaceFirst(contextName, "webapps");
System.out.println("newRequestURI: " + newRequestURI);

The output will be what you're expecting:

输出将是您所期望的:

newRequestURI: /webapps/public/Test.jsp

ideone example.

一个例子。

#2


0  

When referencing a variable, do not surround it in quotes, as that converts it into a literal String object.

引用变量时,不要用引号括起来,因为它将它转换为文字String对象。

String newRequestURI = requestURI.replaceFirst(contextName, "webapps");