2014-02-27 62 views
1

我在以後使用Twitter API時將以下代碼用作測試。JAVA String replaceAll#標籤內容

當我從我的流中獲取推文並將它們存儲在mySQL中時,如何刪除與任何結尾字符一起的hashtags? (基本省略hashtag中的所有內容)

我能夠使用replaceAll並傳遞「#」和「,」值並將它們替換爲「」。它的工作原理和輸出低於代碼,但我將如何使用來替換hashtag的所有內容,包括「not」「#not」?

public class replaceAllTest { 
    public static void main (String args[]){ 
     String sampleString = "This game was amazing, #not"; 

     System.out.println("Before: " + sampleString); 

     sampleString = sampleString.replaceAll("#", ""); 
     sampleString = sampleString.replaceAll(",", ""); 

     System.out.println("After: " + sampleString); 
    } 

} 

從上面的代碼的輸出:

Before: This game was amazing, #not 
After: This game was amazing not 
從上面的代碼預期輸出

Before: This game was amazing, #not 
After: This game was amazing 

任何幫助,將不勝感激,謝謝Z19

+1

我建議你查一下正則表達式的一些入門教程。 '(,?\ s *#[^ \ s] +)+'http://www.rexfiddle.net/r3hU8jT –

+0

謝謝你們三位的幫助。我感謝你的快速回復:) – Z19

回答

4

您需要使用正則表達式

其中 [^\\s]意味着什麼不是空白 "#[^\\s]+ -

如果你期待後面沒有文字孤獨的主題標籤,使用"#[A-Za-z]*"

的在你的問題解決了之後是不是僅僅字母字符更多的井號標籤。

+0

謝謝你的幫助。 :) – Z19

+0

@ Z19你實際上想要使用他的第二個建議,'#[^ \ s] +'。此外,花30分鐘閱讀[正則表達式](http://en.wikipedia.org/wiki/Regular_expression#Syntax)。這是你可以知道的最有用的事情之一。 – MirroredFate

+0

我在(「#[^ \ s] +」,「」)上出現「無效轉義序列」錯誤; – Z19

1

我會去一些像

sampleString = sampleString.replaceAll(",\s+#[A-Za-z]+", ""); 

嘗試使用這個網站,以幫助http://regexpal.com/

+0

你幫了我。謝謝 :) – Z19