在Java中使用正则表达式匹配替换字符串

3

这里的monitorUrl包含 - http://host:8810/solr/admin/stats.jsp
有时,monitorUrl也可能是 - http://host:8810/solr/admin/monitor.jsp

因此,我想将stats.jsp和monitor.jsp替换为ping。

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

以上代码有什么问题。因为我在trimUrl中得到了与monitorUrl相同的值。

3个回答

4

尝试使用replaceAll替代replace(并像Alan指出的那样转义点号):

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

来自文档:

replaceAll

public String replaceAll(String regex, String replacement)

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

注意:您可能还需要考虑仅在斜杠后进行匹配,并使用正则表达式末尾的$检查它是否在行末。

感谢详细的解释。我们如何匹配从最后一个“/”开始直到字符串结尾的内容。由于我对正则表达式非常陌生。 - arsenal
"/(stats|monitor).jsp$" 或者 "(?<=/)(stats|monitor).jsp$" - Mark Byers
@Raihan Jamal:你说的“不起作用”是什么意思?你可以将其替换为“/ping”,而不是“ping”。这样对你行不行? - Mark Byers

3
我认为这就是你要找的内容:

我认为这就是你要找的内容:

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

解释:

  1. replaceAll() 将第一个参数作为正则表达式处理,而 replace() 则将其视为文本字符串。

  2. 使用括号而不是方括号来分组。 (?:...) 是非捕获组形式;只有在确实需要捕获内容时才应使用捕获组形式 - (...)

  3. . 是元字符,因此如果要匹配字面量点,则需要对其进行转义。

最后,您无需单独检查哨兵字符串的存在性;如果它不存在,replaceAll() 就会返回原始字符串。 事实上,replace() 也是如此;您也可以这样做:

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

对于转义点加1,但是最后一行与Zernike的回答存在相同的问题:“" monitor.jsstats.jsp "将变成" pinging "。” - Mark Byers
正确,但根据问题描述,最后一个片段只能是 monitor.jspstats.jsp。这是我理解的方式。 - Alan Moore

1

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

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

1
如果你这样做,"monitor.jsstats.jsp" 将变成 "pinging" - Mark Byers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接