简体   繁体   中英

Replace string by matching with the regular expressions in Java

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.

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.

I think this is what you're looking for:

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

Explanation:

  1. replaceAll() treats the first argument as a regex, while replace() treats it as a literal string.

  2. 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.

  3. . 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");

不需要使用正则表达式(也replace()不使用正则表达式)。

trimUrl = monitorUrl.replace("stats.jsp", "ping").replace("monitor.jsp", "ping");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM