微博发表时候,可以@某人;
开源中国发表动弹时候,发评论时候,可以@某人;
这些都是怎么实现的呢?
我在自己的网站(oscer)实现了这个功能,我分享下我的代码:
/**
* 处理@某人情况,@Timor
*
* @param save_remind
* @param remind_text
* @param sender
* @param type
* @param obj_id
* @param input
* @param max_match_count
*/
public static String fixAt(boolean save_remind, String remind_text, long sender, int type, long obj_id, String input, int max_match_count) {
if (StringUtils.isBlank(input)) {
return "";
}
if (max_match_count <= 0) {
max_match_count = 99999;
}
StringBuilder html = new StringBuilder();
int match_count = 0;
int lastIdx = 0;
Matcher matcher = referer_pattern.matcher(input);
while (matcher.find()) {
match_count++;
String origin_str = matcher.group();
if (match_count <= max_match_count) {
String str = origin_str.substring(1, origin_str.length()).trim();
User user = UserDAO.ME.getUser(str);
if (user != null && user.getId() > 0L) {
html.append("<a href=\"" + LinkTool.user(user.getId()) + "\" class=\"referer\" target=\"_blank\">@");
html.append(str.trim());
html.append("</a> ");
//保存提醒记录
if (save_remind) {
Remind.ME.saveRemind(remind_text, sender, type, obj_id, user.getId());
}
} else {
html.append(origin_str);
}
} else {
html.append(origin_str);
}
lastIdx = matcher.end();
}
html.append(input.substring(lastIdx));
return html.toString();
}
参数解释:
save_remind是否提醒用户,max_match_count可以@多少个人
附上正则表达式:
/**
* @某人
*/
public final static Pattern referer_pattern = Pattern.compile("@([^@^\\s^:^,^;^','^';'^>^<]{1,})");