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):

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

Matched occurrences of a group

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

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:

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

Optional groups

Inline groups match()->group()->all() also handle optional capturing groups.

In this example, we'll match words, with a pattern that specifies an optional capturing group named capital, which is supposed to match a capital letter. Not every word in the subject has a capital letter, so not every occurrence will have group capital matched.

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

Missing or invalid groups

When match()->group() is called with a group that wasn't used in pattern (for example "asd" or 1200), NonexistentGroupException is thrown.CodeTabs

If, however, an invalid group is used:

  • group name starting with a number (e.g. "2asd")
  • negative group index (e.g. -12)
  • group name containing invalid characters (e.g. "!@#")

... then \InvalidArgumentException is thrown.

Last updated on