我将servlet中的电子邮件地址列表作为参数从请求中获取,格式如下:
,Group 4: [abc@xyz.com,asd@dsa.com],,Group 4: [abc@xyz.com],,Group 3: [],,Group 2:
[qwe@rty.com,yui@gui.com,jih@app.com,abc@xyz.com,asd@dsa.com],,Group 1:
[pick@pick.com,test@pick.com,test1@pick1.com],,Nirmal testGroup: [qwe@rty.com],
如何用Java解析所有唯一的电子邮件地址?
群组名称并不重要。此外,组名称不必总是作为组1,组3,它可以是包含空格的任何内容。只需要从字符串中获取所有唯一电子邮件地址的列表/数组。
答案 0 :(得分:2)
使用regex选出方括号([]
)之间的所有内容,然后选择逗号中的每一个split:
String example = ",Group 4: [abc@xyz.com,asd@dsa.com],,Group 4: [abc@xyz.com],,Group 3: [],,Group 2:\n" +
"[qwe@rty.com,yui@gui.com,jih@app.com,abc@xyz.com,asd@dsa.com],,Group 1: \n" +
"[pick@pick.com,test@pick.com,test1@pick1.com],,Nirmal testGroup: [qwe@rty.com],";
Pattern pattern = Pattern.compile("\\[(.*?)\\]");
Matcher matcher = pattern.matcher(example);
while (matcher.find()) {
for (String email : matcher.group(1).split(",")) {
System.out.println(email);
}
}