2012-05-03 53 views
7

我想要在String中的#字符後立即提取任何字,並將它們存儲在String[]數組中。從字符串中提取散列標記

例如,如果這是我的String ...

"Array is the most #important thing in any programming #language" 

然後,我要提取下面的話變成String[]陣列...

"important" 
"language" 

可能有人請提供建議實現這一點。

+3

[你有什麼嘗試?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – user1329572

+4

這應該被標記爲#homework? –

回答

19

試試這個 -

String str="#important thing in #any programming #7 #& "; 
Pattern MY_PATTERN = Pattern.compile("#(\\S+)"); 
Matcher mat = MY_PATTERN.matcher(str); 
List<String> strs=new ArrayList<String>(); 
while (mat.find()) { 
    //System.out.println(mat.group(1)); 
    strs.add(mat.group(1)); 
} 

出來說 -

important 
any 
7 
& 
+0

如何將這些單詞解壓縮到一個String []數組中? – baraaalsafty

+1

@baraaalsafty - 代碼更新(使用列表而不是數組) –

+0

這是正確的謝謝 – baraaalsafty

5

試試這個正則表達式

#\w+ 
12
String str = "Array is the most #important thing in any programming #language"; 
Pattern MY_PATTERN = Pattern.compile("#(\\w+)"); 
Matcher mat = MY_PATTERN.matcher(str); 
while (mat.find()) { 
     System.out.println(mat.group(1)); 
} 

使用的正則表達式是:

#  - A literal # 
(  - Start of capture group 
    \\w+ - One or more word characters 
)  - End of capture group 
+0

非常感謝您 – baraaalsafty

+0

我如何將這些單詞解壓縮到一個String []數組中? – baraaalsafty