Inline groups

Apart from retrieving matched capturing groups, you can also replace by an inline group.

Method match()->group() behaves exactly like Match.group(int|string):

  • it can accept either group index (where #0 is the whole match) or a group name (when a group is named)
  • it throws \InvalidArgumentException for an invalid index or an invalid group name (e.g. "2group" or -2)
  • and throws NonexistentGroupException if group() is used with a non-existent group

Matched occurrences of a group

Similarly to how you can retrieve all matched occurrences of pattern from subject:

  • T-Regx
  • PHP
pattern("(?<capital>[A-Z])[a-z]+")->match("Hello there, General Kenobi")->all();
['Hello', 'General', 'Kenobi']

...you can retrieve all matched occurrences of a capturing group in a subject:

  • T-Regx
  • PHP
pattern("(?<capital>[A-Z])[a-z]+")->match("Hello there, General Kenobi")->group('capital')->all();
['H', 'G', 'K']

Optional groups

What does match()->group()->all() for unmatched capturing group?

  • T-Regx
  • PHP
pattern("(?<capital>[A-Z])?[a-z]+")->match("Hello there, General Kenobi")->group('capital')->all();
['H', null, 'G', 'K']

You guess it :)

Last updated on