frosty
frosty

Reputation: 2649

Having find() find more than once in regex in java

I need find() to find more than once. For example, in the regex below it will only get "i am cool1", but I also want it to get "i am cool2" and "i am cool3". How would I do that?

Pattern pattern = Pattern.compile("i am cool([0-9]{1})", Pattern.CASE_INSENSITIVE);
String theString = "i am cool1 text i am cool2 text i am cool3 text";
Matcher matcher = pattern.matcher(theString);
matcher.find();
whatYouNeed = matcher.group(1);

Upvotes: 0

Views: 46

Answers (1)

lojoe
lojoe

Reputation: 521

You have to invoke find() for every match. You can get the whole match with group() (without index).

    Pattern pattern = Pattern.compile("i am cool([0-9]{1})", Pattern.CASE_INSENSITIVE);
    String theString = "i am cool1 text i am cool2 text i am cool3 text";
    Matcher matcher = pattern.matcher(theString);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }

This will print

i am cool1
i am cool2
i am cool3

Upvotes: 1

Related Questions