【问题标题】:How to use regular expression to remove url which has $?-()如何使用正则表达式删除具有 $?-() 的 url
【发布时间】:2017-07-16 17:07:45
【问题描述】:

原始字符串:

String str = "others. https://forum.com/thread.jspa?thread$ID=251290(tr)start=75&t-start=0 I recently"

目标字符串:

"others. I recently";

我应用了 -Removing the url from text using java 的 11 票答案 但它不适用于我的网址。

感谢您的帮助。

【问题讨论】:

  • 由于您的 URL 不包含 空格,为什么不简单地以这种方式拆分您的字符串?
  • @Seelenvirtuose 哪种方式?

标签: java regex url https


【解决方案1】:

I.如果你总是有结构:word url word(和不带空格的url)你可以使用:

String str = "others. https://forum.com/thread.jspa[...]art=75&t-start=0 I recently";
Matcher m = Pattern.compile("(.*)http.*\\s(.*)").matcher(str); // (capture1)url (capture2)
String target = "";
if (m.find()) {
    target = m.group(1) + m.group(2);
}
System.out.println(target);  //others. recently

该模式将捕获 2 个组,一个在 url 之前,一个在 url 之后的空格之后


II.遍历句子的单词并保留不包含“http”的单词,表示它是一个url

StringBuilder builder = new StringBuilder(); 
for (String word : str.split(" ")) { 
     if (!word.contains("http")) { 
         builder.append(word).append(" "); 
     } 
} 
String target = builder.deleteCharAt(builder.length()-1).toString();
System.out.println(target); //others. recently

III.II. 相同,但有流(ONE LINE 解决方案):

String target = Arrays.asList(str.split(" "))
                      .stream()
                      .filter(word -> !word.contains("http"))
                      .map(word -> word + " ")
                      .collect(Collectors.joining());

【讨论】:

    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2013-01-08
    • 2020-07-12
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多