DEV Community

JianTeng
JianTeng

Posted on

2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
divyanshukatiyar profile image
Divyanshu Katiyar

Very nice and informative post :)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay