[英]Replace string by matching with the regular expressions in Java
here monitorUrl contains- http://host:8810/solr/admin/stats.jsp
这里monitorUrl包含
http://host:8810/solr/admin/stats.jsp
and monitorUrl sometimes can be-- http://host:8810/solr/admin/monitor.jsp
和monitorUrl有时可以是 -
http://host:8810/solr/admin/monitor.jsp
So i want to replace stats.jsp and monitor.jsp to ping 所以我想将stats.jsp和monitor.jsp替换为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.
因为我在trimUrl中获得了相同的monitorUrl值。
Try using replaceAll
instead of replace (and escape the dot as Alan pointed out): 尝试使用
replaceAll
而不是替换(并像Alan指出的那样逃避点):
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: 说明:
replaceAll()
treats the first argument as a regex, while replace()
treats it as a literal string. replaceAll()
将第一个参数视为正则表达式,而replace()
将其视为文字字符串。
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. 如果它不存在,
replaceAll()
只返回原始字符串。 For that matter, so does replace()
; 就此而言,
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.