How to assign names to capture groups in regex?
The syntax to assign a name to a capture group is (?<captureGroupName>patternToMatch).
Let’s see an example :
// Javascript code
var str = "My birth date is 1976-09-28. Remember this.";
var matchExp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
var result = matchExp.exec(str);
console.log("Year : " + result.groups.year);
console.log("Month : " + result.groups.month);
console.log("Day : " + result.groups.day);
Output :
Year : 1976
Month : 09
Day : 28
Let’s understand the regular expression here :
In this javascript code the regular expression is assigned to matchExp is
(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})
(?<year>\d{4}) : In this portion (?< refers to the starting of named captured group, year this is the group name, > ends the group name and \d{4} refers 4 digit number and ) refers to the end of capture group.
So when we write result.groups.year
in console.log("Year : " + result.groups.year);
the year
refers to the group name.
(?<month>\d{2}) and (?<day>\d{2}) works same way as (?<year>\d{4}).
1 Comment