2011-02-25 28 views
7

我想查找以「#」符號開頭的單詞,該單詞在java中是一個字符串。標誌和單詞之間也可以有空格。查找單詞從特殊字符開始java

"hi #how are # you"鬚髮出輸出:

how 
you 

我已經和正則表達式試過,但還是沒能找到一個合適的模式。請幫助我。

謝謝。

回答

10

使用#\s*(\w+)作爲您的正則表達式。

String yourString = "hi #how are # you"; 
Matcher matcher = Pattern.compile("#\\s*(\\w+)").matcher(yourString); 
while (matcher.find()) { 
    System.out.println(matcher.group(1)); 
} 

這將打印出:

how 
you 
+0

感謝您的幫助ide,喬和knutson。有用。我也想獲得所有在最後一個#符號後出現的單詞。 '例如:「嗨#how是#你在做什麼」應該給出輸出結果作爲你如何去做「是否有實現這一點? – gishara 2011-02-25 06:34:10

+0

這是一個不同的問題,雖然你可以用正則表達式來解決它(''Pattern.compile(「#\\ s *([^#] + $ | \\ w +)」)'),但它可能會讓人困惑...... – ide 2011-02-25 06:39:43

+0

非常感謝您的幫助。那是我想要的。 :) – gishara 2011-02-25 06:43:56

0

試試這個表達式:

# *(\w+) 

此說,比賽#然後匹配0或多個空格和1個或多個字母

+0

爲什麼在字符類的空間? – NullUserException 2011-02-25 06:24:20

+0

我在想我自己,thx – Joe 2011-02-25 06:25:36

0

我想你可能是最好關閉使用拆分方法上的字符串( mystring.split(''))並分別處理這兩個案例。如果你要讓多人更新代碼,正則表達式可能很難維護和閱讀。

if (word.charAt(0) == '#') { 
    if (word.length() == 1) { 
    // use next word 
    } else { 
    // just use current word without the # 
    } 
} 
0

這裏有一個非正則表達式的方法...

  1. 替換#,然後在你的字符串與空間的所有出現a#

    myString.replaceAll(「\ s#」,「#」)

  2. 現在使用空間作爲分隔字符

    字符串[]字=​​ myString.split(」「)

  3. 最後迭代你的話,檢查前導字符的字符串分割成令牌

    word.startsWith( 「#」)

-1
 String mSentence = "The quick brown fox jumped over the lazy dog."; 

     int juIndex = mSentence.indexOf("ju"); 
     System.out.println("position of jumped= "+juIndex); 
     System.out.println(mSentence.substring(juIndex, juIndex+15)); 

     output : jumped over the 
     its working code...enjoy:)