我正在用正則表達式構建一個簡單的twitter用戶提到查找器。JAVA匹配組
public static Set<String> getMentionedUsers(List<Tweet> tweets) {
Set<String> mentionedUsers = new TreeSet<>();
String regex = "(?<=^|(?<=[^a-zA-Z0-9-_\\\\.]))@([A-Za-z][A-Za-z0-9_]+)";
for(Tweet tweet : tweets){
Matcher matcher = Pattern.compile(regex).matcher(tweet.getText().toLowerCase());
if(matcher.find()) {
mentionedUsers.add(matcher.group(0));
}
}
return mentionedUsers;
}
而且它未能找到匹配,如果表達式爲文本例如結束「@格洛弗告訴我@GREG」它只返回「@格洛弗」。
您是否記住group(0)是您的正則表達式的完整匹配,而group(1)將會是您在正則表達式中定義的第一個捕獲組內的內容? –