Alex Rivera | Logout

Finding all of the matching substrings, not only the "most extended" one

Asked 2012-06-27T14:21:49.870
13

The code

String s = "y z a a a b c c z";
Pattern p = Pattern.compile("(a )+(b )+(c *)c");
Matcher m = p.matcher(s);
while (m.find()) {
    System.out.println(m.group());
}

prints

a a a b c c

which is right.

But logically, the substrings

a a a b c
a a b c c
a a b c
a b c c
a b c

match the regex too.

So, how can I make the code find those substrings too, i.e. not only the most extended one, but also its children?

Edit
Report

1 Answer

0

The only way I can think of here would be to generate a list of all possible substrings of your original string and match the regex against each of them, retaining those items where it matched.

answered 2012-06-27T15:28:32.287

Your Answer