Regular Expression Match Groups

By  on  

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:

https://twitter.com/addyosmani/status/1386031624232456194

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!

Recent Features

  • By
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

  • By
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

Incredible Demos

  • By
    HTML5&#8217;s placeholder Attribute

    HTML5 has introduced many features to the browser;  some HTML-based, some in the form of JavaScript APIs, but all of them useful.  One of my favorites if the introduction of the placeholder attribute to INPUT elements.  The placeholder attribute shows text in a field until the...

  • By
    Create a Sexy Persistent Header with Opacity Using MooTools or jQuery

    I've been working with the Magento eCommerce solution a lot lately and I've taken a liking to a technique they use with the top bar within their administrative control panel. When the user scrolls below a specified threshold, the top bar becomes attached to the...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!