Wahedsaw
Wahedsaw

Reputation: 397

loop through one group in regex (Java)

I have a regex containing something like ([A-Za-z]\s)+. It returns one group containing all the letters followed by a space. However, it keeps only the last element in the group for example if the text contains a b c d, I tried to print the group match but it returns only the letter (d). This is my program

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

My question is why I only get letter (d) instead of all letters? Is it because They are all captured through one group? how can I correct that? How can I iterate through one group. For example, iterate through all matches detected as one group?

Upvotes: 1

Views: 1216

Answers (1)

Didier L
Didier L

Reputation: 20579

The problem with your regex is that it matches all sequences of one character followed by a space.

In your example, group() would return the whole a b c d string. However when capturing braces are inside repetition (like your +), only the last captured value can be retrieved, hence group(1) returns d.

To fix your issue, just remove the + from your regex. This will make the find() succeed several times, and each time you will get a different match. In that case you might even drop the parenthesis and simply use group().

Upvotes: 2

Related Questions