Reputation: 24144
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.
Upvotes: 3
Views: 3508
Reputation: 838076
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.
Upvotes: 4
Reputation: 75222
I think this is what you're looking for:
trimUrl = monitorUrl.replaceAll("(?:stats|monitor)\\.jsp", "ping");
Explanation:
replaceAll()
treats the first argument as a regex, while replace()
treats it as a literal string.
You use parentheses, not square brackets, to group things. (?:...)
is the non-capturing form of group; you should use the capturing form - (...)
- only when you really need to capture something.
.
is a metacharacter, so you need to escape it if you want to match a literal dot.
And finally, you don't have to check for the presence of the sentinel string separately; if it's not there, replaceAll()
just returns the original string. For that matter, so does replace()
; you could also have done this:
trimUrl = monitorUrl.replace("stats.jsp", "ping")
.replace("monitor.jsp", "ping");
Upvotes: 3
Reputation: 1766
No needs to use regex (also replace()
don't use regex).
trimUrl = monitorUrl.replace("stats.jsp", "ping").replace("monitor.jsp", "ping");
Upvotes: 1