DEV Community

JianTeng
JianTeng

Posted on

Extract dynamic text using regex capturing group

We can quickly extract dynamic text using regex capturing group. It is useful when we want to extract information from a bunch of strings that are using the same words.

const example = 'You have bought 2 tickets'
const regex = /You have bought (?<tickets>\d*) tickets/
const match = example.match(regex);

console.log(match.groups.tickets);
// output: 2
Enter fullscreen mode Exit fullscreen mode

In the example above, we want to extract the number of tickets from the string You have bought 2 tickets. We can define a regular expression pattern by enclosing it between slashes.

Next, we can define the named capturing group using (?<Name>x). We can access it in the match.groups object.

Here's an example where we extract multiple text.

const example = 'You have bought 2 tickets and 5 drinks'
const regex = /You have bought (?<tickets>\d*) tickets and (?<drinks>\d*) drinks/
const match = example.match(regex);

console.log(match.groups);
/*
output: { tickets: '2', drinks: '5' }
*/
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
divyanshukatiyar profile image
Divyanshu Katiyar

Very nice and informative post :)