/**
* 微博内容中的at正则表达式
*/
private final Pattern AT_PATTERN = Pattern.compile("@[\\u4e00-\\u9fa5\\w\\-]+");
/**
* 微博内容中的#话题#正则表达式
*/
private final Pattern TAG_PATTERN = Pattern.compile("#([^\\#|.]+)#");
Matcher m = TAG_PATTERN.matcher(content);
while (m.find()) {
String tagNameMatch = m.group();
}
Matcher m = AT_PATTERN.matcher(content);
while (m.find()) {
String atUserName = m.group();
}
补充一个,应该是常识了:
根据 Java Language Specification 的要求,Java 源代码的字符串中的反斜线被解释为 Unicode 转义 或其他字符转义 。因此必须在字符串字面值中使用两个反斜线,表示正则表达式受到保护,不被 Java 字节码编译器解释。例如,当解释为正则表达式时,字符串字面值 "\b" 与单个退格字符匹配,而 "\\b" 与单词边界匹配。字符串字面值 "\(hello\)" 是非法的,将导致编译时错误;要与字符串 (hello) 匹配,必须使用字符串字面值 "\\(hello\\)" 。