Harry Joy
Harry Joy

Reputation: 59686

How to parse this string to extract email addresses?

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

,Group 4: [[email protected],[email protected]],,Group 4: [[email protected]],,Group 3: [],,Group 2:
[[email protected],[email protected],[email protected],[email protected],[email protected]],,Group 1: 
[[email protected],[email protected],[email protected]],,Nirmal testGroup: [[email protected]],

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.

Upvotes: 1

Views: 3078

Answers (1)

Ryan Stewart
Ryan Stewart

Reputation: 128909

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

String example = ",Group 4: [[email protected],[email protected]],,Group 4: [[email protected]],,Group 3: [],,Group 2:\n" +
                         "[[email protected],[email protected],[email protected],[email protected],[email protected]],,Group 1: \n" +
                         "[[email protected],[email protected],[email protected]],,Nirmal testGroup: [[email protected]],";
Pattern pattern = Pattern.compile("\\[(.*?)\\]");
Matcher matcher = pattern.matcher(example);
while (matcher.find()) {
    for (String email : matcher.group(1).split(",")) {
        System.out.println(email);
    }
}

Upvotes: 2

Related Questions