loading...

Regex Named Capturing Groups in JavaScript and Node

educobuci profile image Eduardo Cobuci Updated on ・1 min read

Capturing groups are one of the most useful feature of regular expressions, and the possibility to name groups make them even more powerful.

How it works?

Imagine that you have a list of files that are named in a structured way, for example 1_create_users_table.sql, where the number represents some code and the following part a name. So it is [code]_[name].sql.

Now instead of parsing those file names, maybe using split or something, you could just write a regex to precisely identify each portion of the string and return them individually? Easy peasy with named capturing groups!

const regex = /(?<code>\d+)_(?<name>\S+)\.sql/;
const fileName = '1_create_users_table.sql';
const groups = fileName.match(regex).groups;
console.log(groups.code);  // 1
console.log(groups.name);  // create_users_table

As you can see in the example above, we can specify the name of a capturing group by using the (?<group-name>...) syntax and the regex engine does the job of returning each group name into the groups property. It is that simple!

Do you like it, was it helpful? Please give your like or leave a comment!

Thanks!

Discussion

markdown guide