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?
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 wholea b c dstring. However when capturing braces are inside repetition (like your+), only the last captured value can be retrieved, hencegroup(1)returnsd.To fix your issue, just remove the
+from your regex. This will make thefind()succeed several times, and each time you will get a different match. In that case you might even drop the parenthesis and simply usegroup().