Regular expressions and text guides

Named regex groups: readable extraction and optional fields

Use named groups for field extraction and distinguish an unmatched optional group from an empty match.

Nav Tools ·

Give each field a stable name

Named groups expose fields by name instead of by a numeric index that changes when a group is inserted earlier.

Test a small key-value line and inspect the match in JavaScript; the site uses that regex flavor.

const m = /^(?<key>[a-z]+)=(?<value>\d+)$/.exec('count=42');
m.groups → {key:'count',value:'42'}

Check optional participation

A named group in an optional branch can be undefined when that branch does not match. A participating group that matches nothing is an empty string.

Do not use truthiness alone if these two states have different meanings in your parser.

/^(?<name>[a-z]+)(?:=(?<value>\d*))?$/.exec('count').groups.value → undefined
Same pattern on 'count=' → ''

Use names in replacement templates

JavaScript replacement strings can use

lt;name> for named captures. This keeps a field reordering readable.

In Regex Replace, enter the pattern, flags and replacement as JSON; escape backslashes at the JSON layer as required.

{"pattern":"(?<key>[a-z]+)=(?<value>\\d+)","flags":"g","replacement":"
lt;value>:
lt;key>"}

Confirm runtime support and uniqueness

Named groups require runtime support. Reusing a name across alternatives has compatibility nuances, so distinct names are the safer portable fixture.

Validate the extracted string's meaning separately; naming a group value does not turn numeric text into a number.

References

← Regular expressions and text guides