2017-07-16 59 views
-3

產地字符串:

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

目標字符串:

"others. I recently"; 

我申請的11票的答案 - Removing the url from text using java 但它沒有在我的網址上工作。

感謝您的幫助。

+0

您的網址不包含_spaces_,何不乾脆拆你的字符串這樣? – Seelenvirtuose

+0

@Seelenvirtuose哪種方式? –

+2

['String.split'](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-)? – Seelenvirtuose

回答

0

如果你所要的struture:字字的URL(和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之前的一個,和之後的空格


二,遍歷句子的單詞,並保持不包含「HTTP」,這significate,它是一個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的人。二,但王氏流(一行溶液):

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