1

I'm getting list of email addresses in a servlet as a parameter in from request in following format:

,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],

How can I parse all unique email addresses from this in Java?

Group names are not important. Also it is not necessary that a group name will be always as Group 1, Group 3, it can be anything containing spaces. Just need to have list/array of all unique email addresses from the string.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Harry Joy
  • 58,650
  • 30
  • 162
  • 207

1 Answers1

2

Use a regex to pick out everything between square brackets ([]), then split each of those on the commas:

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);
    }
}
Ryan Stewart
  • 126,015
  • 21
  • 180
  • 199