从String中提取哈希标记

时间:2012-05-03 13:35:51

标签: java extract

我想在#中的String字符后立即提取任何字词,并将其存储在String[]数组中。

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

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

然后我想将以下单词提取到String[]数组......

"important"
"language"

有人可以提供实现此目的的建议。

3 个答案:

答案 0 :(得分:22)

试试这个 -

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));
}

out put -

important
any
7
& 

答案 1 :(得分:13)

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

答案 2 :(得分:5)

试试这个正则表达式

#\w+