检查String是否包含主题标签字

时间:2015-12-02 15:56:17

标签: java string

如果输入字符串包含hashtag字并获取它,如何有效检查?

实例:

String input = "My name is #George and I like #Java."
String[] hashTag = getHashTag(input);
Results are: #George, #Java

感谢您的回复。

3 个答案:

答案 0 :(得分:0)

尝试使用它:

  String input = "My name is #George and I like #Java.";
             Pattern patt = Pattern.compile("(#\\w+)\\b");
             Matcher match = patt.matcher(input);
             List<String> matStr =new ArrayList<String>();
             while (match.find()) {
                 matStr.add(match.group(1));
            }
                 System.out.println("Results are: "+matStr.get(0)+" , " +matStr.get(1));

输出:

Results are: #George , #Java

答案 1 :(得分:0)

    String input = "My name is #George and I like #Java.";
    Matcher m = Pattern.compile("(#\\w+)\\b",Pattern.CASE_INSENSITIVE).matcher(input);
    while(m.find()){
        System.out.println(m.group(1));
    }

输出:

#George
#Java

试试这个LINK

答案 2 :(得分:0)

这可以使用正则表达式完成:

private static String[] getHashTag(String str) {
    ArrayList<String> allMatches = new ArrayList<String>();
    Matcher m = Pattern.compile("(#\\w+)\\b").matcher(str);
    while (m.find()) {
        allMatches.add(m.group());
    }
    return allMatches.toArray(new String[0]);
}

可以使用您的专栏调用此代码:String[] hashTag = getHashTag(input);