【问题标题】:Java Regex replace : and / except the domain name in the url to white spaceJava Regex 将 : 和 / 除了 url 中的域名替换为空格
【发布时间】:2017-03-20 01:52:08
【问题描述】:

我有一个很长的字符串,包括很多 :/。它还包括网址。

我想将所有:/ 替换为空格,但网址的域名(例如http://example.com)。

所以link:http://example.com/test/page.html 将变为link http://example.com test page.html

我尝试了replaceAll("[://]", " "),但它也将http://example.com 中的:/ 替换为空白。

【问题讨论】:

  • 替换还是删除?
  • 替换为空白,如示例所示。
  • 你的代码应该如何响应url:http://example.com//foo/bar
  • 你为什么不用replaceFirst()
  • 应该给url http://example.com foo bar

标签: java regex url


【解决方案1】:

由于您需要在一个上下文中保留一些模式并在另一个上下文中替换为其他内容,因此您可以使用正则表达式来匹配和捕获 URL(以及您想要“保护”的任何内容)和只需匹配您需要删除的内容。然后,使用Matcher#appendReplacement() 检查捕获是否发生,并相应地使用适当的替换。

正则表达式可以类似于(\\bhttps?://\\S*)|[:/],其中(\\bhttps?://) 匹配并捕获到第1 组 http://https://,而[:/] 匹配: 或@987654331 @(替换为空格)。如果您需要“缩小”/s 和 :s,请使用 [:/]+

这是一个示例代码:

String fileText = "http://example.com//foo/bar http://example.com//foo/bar  1: 2/";
String pattern = "(\\bhttps?://)|[:/]";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(fileText);
StringBuffer sb = new StringBuffer();
while (m.find()) {
    if (m.group(1) != null)
        m.appendReplacement(sb, m.group(1));
    else
        m.appendReplacement(sb, " ");
}
m.appendTail(sb);
System.out.println(sb);
// => http://example.com  foo bar http://example.com  foo bar  1  2

请参阅Java demo

【讨论】:

  • 我看不出这是如何产生预期结果的?当我运行它时,我得到“example.com//foo/bar 1 2”
  • @MichaelMarkidis 你是对的。它不会将//fo/bar 替换为fo bar
  • “不替换 //fo/bar 到 fo bar”是什么意思?应该是?见ideone.com/lzACQw
  • 我明白了,在编辑之前,我的答案是 100% 正确的,现在,它也正确了,但是 Pshemo 的方法更简洁。
  • @WiktorStribiżew 您的答案现在 100% 正确,但在编辑之前,模式是 "(\\bhttps?://\\S*)|[:/]",没有将 //fo/bar 替换为 foo bar。还是谢谢。
【解决方案2】:

现在看起来你可能想要使用类似的东西:

url = url.replaceAll("(https?://[^/:]+)?[/:]", "$1 ")

$1 表示来自第 1 组的匹配 (https?://[^/:]+),这要归功于 ? 是可选的。

所以它会尝试找到任何/: 并将其替换为空格。如果在这些字符中的任何一个之前有 http://address 部分,它将被自己替换。

【讨论】:

    猜你喜欢
    • 2021-10-01
    • 2020-09-12
    • 2022-10-13
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多