0
 Input String : "slack,users@xyz.com , slack,auditors@xyz.com , abc@xyz.com"

Regex I am using :

(.+?)@(.+?),

Current Output :

Group 0 - slack,users@xyz.com ,
Group 1 - slack,auditors@xyz.com ,

The output I want :

Group 0 - slack,users@xyz.com
Group 1 - slack,auditors@xyz.com
Group 2 - abc@xyz.com

My Code :

    String regex = "(.+?)@(.+?),";       
    Pattern pattern = Pattern.compile(regex);
    Matcher m =pattern.matcher("slack,users@xyz.com , slack,auditors@xyz.com , abc@xyz.com");


    while(m.find()){
       System.out.println(m.group());
    }

How do I modify my regex so that it will make the ending comma optional so that the last group in the form of "user@domain" is also matched?

Also, how can i split the string in some way so that the ending comma is not part of the resulting groups?

WillMcavoy
  • 1,795
  • 4
  • 22
  • 34
  • 1
    Instead of `,`, use `(?:,|$)`. – 41686d6564 stands w. Palestine Feb 11 '20 at 21:54
  • 1
    Or better, `([^,]+)` instead of `(.+?),` – Wiktor Stribiżew Feb 11 '20 at 21:55
  • This could be underkill, but if your input is always the same format, why not split on ` , ` (space, comma, space) ? – Xhattam Feb 11 '20 at 22:02
  • This seems to work: `(?:\w*,|)\w*@\w*\.\w*` Let's have a look at the parts, with the first element of your list: - `(?:\w*,|)` non-capturing group that will look the `slack,` element - `\w*` looks for a word/number/underscore, n times, like the `user` element - `@` is literal - `\w*` looks for another word/number/underscore, n times, like the `xyz` element - `\.` will match a literal `.` - `\w*` again to match the domain name – Xhattam Feb 11 '20 at 22:13

0 Answers0