Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string by matching with the regular expressions in Java

Tags:

java

regex

here monitorUrl contains- http://host:8810/solr/admin/stats.jsp
and monitorUrl sometimes can be-- http://host:8810/solr/admin/monitor.jsp

So i want to replace stats.jsp and monitor.jsp to ping

if(monitorUrl.contains("stats.jsp") || monitorUrl.contains("monitor.jsp")) {
                trimUrl = monitorUrl.replace("[stats|monitor].jsp", "ping");
            }

Anything wrong with the above code. As I get the same value of monitorUrl in trimUrl.

like image 778
arsenal Avatar asked Apr 22 '26 03:04

arsenal


1 Answers

Try using replaceAll instead of replace (and escape the dot as Alan pointed out):

trimUrl = monitorUrl.replaceAll("(stats|monitor)\\.jsp", "ping");

From the documentation:

replaceAll

public String replaceAll(String regex, String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement.


Note: You may also want to consider matching only after a / and checking that it is at the end of the line by using $ at the end of your regular expression.

like image 67
Mark Byers Avatar answered Apr 24 '26 19:04

Mark Byers