Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

9
  • 12
    "Capturing a repeated group captures all iterations." In your regex101 try to replace your regex with (\w+),? and it will give you the same result. The key here is the g flag which repeats your pattern to match into multiple groups. Commented Jan 22, 2021 at 11:21
  • 1
    This is so wrong. "Capturing a repeated group captures all iterations": yes but it will capture ALL of them in only ONE match (containing them all). Your example should be ((?:\w,?)+) . You have multiple matches here only because of the g flag as @thomas-laurent stated. There is no way to have multiple matches from one capturing group. You have to extract and preg_match_all (or equivalent function) the repeating group.
    – Pierre
    Commented Dec 23, 2021 at 14:36
  • @Pierre Thanks for your clarification. Based on the original question(s), we have to make an assumption about what is needed. First, he said, "I want to capture every word, so that Group 1 is: HELLO…Group 3 is WORLD…" Your distinction is important because unique backreference groups are necessary for this case. The table above shows all matchs assigned to Group 1. As a result, ((?:\w+)+),? does not work. Going on to sum up, he said, "I need to capture all the groups that match the pattern, not only the last one." ((?:\w+)+),? accomplishes this with the g flag enabled.
    – ssent1
    Commented Jan 8, 2022 at 16:53
  • 2
    @ssent1 Your ((?:\w+)+),? is equivalent to (\w+),?. Your enclosing anonymous group is never repeated. This misleading, there is nothing like "capturing a repetated group [in multiple matches]". Unfortunately, nothing in regexp can match multiple times the same group. There is only the g flag and preg_match_all that executes the regexp iteratively on the remaining unmatched string.
    – Pierre
    Commented Jan 9, 2022 at 17:38
  • 1
    @Pierre You're correct. And yet it seems like there is still a distinction to be made between [Repeating a Capturing Group vs. Capturing a Repeated Group])(regular-expressions.info/captureall.html). On a practical level, it could be part of a functional solution. Ultimately, if a 'bulletproof' solution is needed, it's probably better to do it programmatically.
    – ssent1
    Commented Feb 17, 2022 at 16:45