Search code examples
javaandroidstringlistmatcher

get list of string with matcher in java/android


I have a string like

number +919999999990  time at:07:42:45 on 10.04.2014, number
+919999999991 time at:08:42:45 on 11.05.2014,  number +919999999992 time at:075:42:45 on 05.03.2014 , number +9199999999913 ,time at:27:40:45 on 09.04.2015.

I have to retrieve all phone-numbers , date and time . I am planning to use pattern and matcher.

My code is

String extra1="number +919999999990  time at:07:42:45 on 10.04.2014, number +919999999991 time at:08:42:45 on 11.05.2014, number +919999999992 time at:075:42:45 on 05.03.2014 , number +9199999999913 ,time at:27:40:45 on 09.04.2015.";
Pattern pattern = Pattern.compile("\\+\\d{12}");
Matcher matcher = pattern.matcher(extra1);
System.out.println("matcher.groupCount() "+matcher.groupCount());
if (matcher.find()) {
    while(matcher.find()) {
        System.out.println(matcher.group());
    }   
} else {
     System.out.println("Not Found");
}

According to this and this it should print all the phone numbers. But I am getting only the first phone number.

Can anyone suggest a solution...


Solution

  • If you remove the ´if (matcher...)´statement wich will consume the first number, it works fine for me:

        String extra1 = "number +919999999990  time at:07:42:45 on 10.04.2014, number +919999999991 time at:08:42:45 on 11.05.2014, number +919999999992 time at:075:42:45 on 05.03.2014 , number +9199999999913 ,time at:27:40:45 on 09.04.2015.";
        Pattern pattern = Pattern.compile("\\+\\d{12}");
        Matcher matcher = pattern.matcher(extra1);
        System.out.println("matcher.groupCount() " + matcher.groupCount());
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    

    output:

    matcher.groupCount() 0
    +919999999990
    +919999999991
    +919999999992
    +919999999991