Monday, 26 April, 2021 UTC


Summary

Regular expressions are incredibly powerful but can be difficult to maintain. They’re a skill you learn on the job and, when the suits walk by, make you look incredibly smart if you have a few up on your screen. How can we solve the maintainability problem? With a match groups, as Addy Osmani enlightened me about last week:
Tip: You can name capture groups for Regular Expressions in JavaScript. Define a named capture in angle brackets <> and they get returned under .groups. pic.twitter.com/Fmj1B9Dgl0
— Addy Osmani (@addyosmani) April 24, 2021
Look at the ?<descriptor> pattern, with the descriptor being a meaningful name that you want to give to a give group. With the group usage, you can more intelligently handle match results:
const re = /(?\d{4})-(?\d{2})-(?\d{2})/;
const result = re.exec('2021-04-26');

// Deconstructing from result.groups
const { year, month, day } = result.groups;

// Using array syntax
const [, year, month, day] = result;
The only real downside of using this strategy is that most developers probably don’t know about it. You could also complain that it makes the regular expression longer. In the end, however, maintainability rules the day, and I love that Addy shared this tip with us!
The post Regular Expression Match Groups appeared first on David Walsh Blog.