1

How can I get patterns using find() method and store the matched patterns in a arraylist

Input string: 9547235617/7865421341

I want to fetch both numbers and pass it in to an arrary list.

Current I am using the below pattern compile method to find the patterns as follows

Pattern number = Pattern.compile("^[789]\\d{9}$");
        Matcher matcher = number.matcher(list_string);
        if (!matcher.matches()) {
            arraylist.add("No number available");
        }

    elseif (matcher.find()) {
                    arraylist.add(matcher.group());
                }
Log.e("Arraylist value is","==>"+arraylist.tostring());

In this methods it always go the the first if condition and when a try to run the same string in other regex testing program on online examples it only matches the last number as pattern I don't have any idea what to do next hope some one can help

output: Arraylist value is ==>No number available

Note: I need to fetch both numbers and add it to array list.Currently I have used splits for special characters and store those splits in to array list but i want a method regarding regex pattern matching.

krishank Tripathi
  • 616
  • 1
  • 7
  • 23

1 Answers1

1

matches() will only return true if the full string is matched. find() will try to find the next occurrence within the substring that matches the regex.

Regex: (?<=^|\/)(?:\b[7-9]\d{9}\b)?

Java code:

String[] aStr = {"9547235617/7865421341", "6547235617/5865421341", "4547235617/9865421341"};

for(String str: aStr) {
    Matcher matcher = Pattern.compile("(?<=^|\\/)(?:\\b[7-9]\\d{9}\\b)?").matcher(str);
    while(matcher.find()){
        if(matcher.group().equals("")) {
            System.out.print("No number available" + "\n");
        } else {
            System.out.print(matcher.group() + "\n");
        }
    }
}

Output:

9547235617
7865421341
No number available
No number available
No number available
9865421341

Code demo

Srdjan M.
  • 3,310
  • 3
  • 13
  • 34