import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author XXX
* Date: 2019/3/20
* Description:
*/
public class RegexpUtil {
/**
* topicTagPattern 匹配话题正则表达式
*/
private static final Pattern topicTagPattern = Pattern.compile("#([^#]{1,40})#");
public static Set<String> getTopicList(String content){
Set<String> topicList = new LinkedHashSet<>();
Matcher matcher = topicTagPattern.matcher(content);
while (matcher.find()){
String topicName = matcher.group(1);
topicList.add(topicName);
}
return topicList;
}
public static void main(String[] args){
String str = "#哈哈a###这是一个#好####哈哈a##哈#啊圣诞节疯狂#奥斯卡级代付款##as的开发#";
Set<String> topicList = getTopicList(str);
System.out.println(topicList);
}
}
输出:
[哈哈a, 这是一个, 哈, 奥斯卡级代付款, as的开发]
新浪微博的话题长度限制好像是40个字符,
另外 类似 #1#2#3# 只有1,3 才算话题 2不算 相当于 一但匹配成功一个话题 ,二个# 符号就会被消耗。
如果需要返回包含重复的话题,getTopicList 方法返回参数改为 List 就好。