0

I have a regular expression:

l:([0-9]+)

This should match this string and return three captures (according to Rubular)

"l:32, l:98, l:234"

Here is my code:

Pattern p ...
Matcher m = p.matcher(...);
m.find();
System.out.println(m.groupCount());

This prints out 1 (group) when there are three, so I can only do m.group(1) which will only return 32.

4 Answers 4

3

Calling Matcher.find finds the next instance of the match, or returns false if there are no more. Try calling it three times and see if you have all your expected groups.

To clarify, m.group(1) is trying to find the first group expression in your regular expression. You only have one such group expression in your regex, so group(2) would never make sense. You probably need to call m.find() in a loop until it returns false, grabbing the group result at each iteration.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works. I am simply doing while (m.find()) ... m.group(1) ... like @Deco said
1

I think it needs to be

Pattern p ...
Matcher m = p.matcher(...);
int count = 0;

while(m.find()) {
    count++;
}
System.out.println(count);

find looks for the next match, so using a while loop will find all matches.

Comments

1

Matcher.find() returns false when there are no more matches, so you can do a while loop whilst getting and processing each group. For example, if you want to print all matches, you can use the following:

    Matcher m;
    Pattern p = Pattern.compile("l:([0-9]+)");
    m = p.matcher("l:32, l:98, l:1234");

    while (m.find()) {
        System.out.println(m.group());
    }

Comments

1

If input string format is fixed you could use following regex

"l:32, l:98, l:234".split("(, )?l:")

Output

[, 32, 98, 234]

2 Comments

That's a good approach, but this example that I gave is an extremely simplified version of what I'm actually trying to accomplish.
what you see(k) is what you get ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.