Search code examples
javastringmatcher

Matcher Class Java - Matching Multiple Sub-strings on Same Line


I am working on a class for which its purpose is to look in a line (string) of text, and to find all strings or sub-strings for which contain certain specific characters, in this case characters "ABC123".

The current code I have written partially works, but only finds the first sub-string in a line of text... in other words, if the line of text that it is looking at contains multiple sub-strings which contain "ABC123", it only finds and returns the first sub-string.

How can I modify the code so that it finds ALL substrings within the line of text?

Below my current code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
//For grabbing the Sub-string and separating it with white space


public class GrabBLSubString {
    public static void main(String[] args) {
        test("Viuhaskfdksjfkds  ABC1234975723434 fkdsjkfjaksjfklsdakldjsen ABC123xyxyxyxyxyxyxyxyxyx");
        test("ABC1234975723434");
        test("Viuhaskfdksjfkds  APLIC4975723434 fkdsjkfjaksjfklsdakldjsen");
        test("abc ABC12349-75(723)4$34 xyz");
    }
    private static void test(String text) {
        Matcher m = Pattern.compile("\\bABC123.*?\\b").matcher(text);//"\\bABC123.*?\\b"____Word boundary // (?<=^|\s)ABC123\S*__For White spaces
        if (m.find()) {
            System.out.println(m.group());
        } else {
            System.out.println("Not found: " + text);
        }
    }
}

As you can see, this code returns the following:

APLU4975723434
APLU4975723434
Not found: Viuhaskfdksjfkds  APLIC4975723434 fkdsjkfjaksjfklsdakldjsen
APLU49

and does not find (Which I want it to!!) the text "ABC123xyxyxyxyxyxyxyxyxyx" on the first line.

Thanks for your help!


Solution

  • Use a loop inside your if block to cover any other instances of your test string.

    if (m.find()) {
        System.out.print(m.group() + " ");
        while (m.find()) {
            System.out.print(m.group() + " ");
        }
    } else {
        System.out.println("Not found: " + text);
    }