-1

I'm running the next code:

Pattern p = Pattern.compile("(<http:.*>)");
    Matcher m = p.matcher("<http:fluffy1@cisco.com>,<http:fluffy2@cisco.com>");
    if (m.find()) {
        int groupCount = m.groupCount();
        for(int i = 0; i < groupCount; i++){
            String groupValue = m.group(i);
            System.out.println(groupValue);
        }
    } else {
        System.out.println("nothing was fined");
    }

And as output I have only one group value: "http:fluffy1@cisco.com,http:fluffy2@cisco.com" But I expect that there should be two groups : Group_1: http:fluffy1@cisco.com Group_2: http:fluffy2@cisco.com

How should I change my regex to achieve this?

Thanks!

denis
  • 77
  • 6

3 Answers3

1

It's not group. It will be group if your pattern look like "(http:.*)(http:.*)". Group is expression between parentheses. Try this:

Pattern p = Pattern.compile("(<http:([^>]+)>)");
Matcher m = p.matcher("<http:fluffy1@cisco.com>,<http:fluffy2@cisco.com>");
while (m.find()) {
    String groupValue = m.group(1); // m.group(2) for email only without http: and <>
    System.out.println(groupValue);
}
User9123
  • 1,643
  • 1
  • 8
  • 21
0

Please refer below code:

   Pattern p = Pattern.compile("(<http:.*?>)");
    Matcher m = p.matcher("<http:fluffy1@cisco.com> , <http:fluffy2@cisco.com>");
    if (m.find()) {
        int groupCount = m.groupCount();
        for(int i = 0; i <= groupCount; i++){
            String groupValue = m.group(i);
            System.out.println("Group("+i+")"+groupValue);
        }
    } else {
        System.out.println("nothing was fined");
    }

Hope this will help you.

chaitanya dalvi
  • 1,539
  • 2
  • 17
  • 25
0

As @user3783243 suggested in one of the comments, you could change the regex to a non-greedy (lazy) evaluation, by adding a ? to the * quantifier:

*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)

The resulting regex would be:

(<http:.*?>)

Here's the test for it: https://regex101.com/r/7751x9/1

Alexandru Somai
  • 1,395
  • 1
  • 7
  • 16