Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Obtain substrings from matching regex

I have this regex

const regex = new RegExp(/^\${[a-z][a-z0-9_]*}\/\${[a-z][a-z0-9_]*}$/, 'g');

that matches the string "${total_123}/${number_items}". Next, I want to extract the substrings total123 and number_items and set them as

const numerator = total_123 and const denominator = number_items. I’m not exactly sure how to do so.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const regex = new RegExp(/^\${([a-z][a-z0-9_]*)}\/\${([a-z][a-z0-9_]*)}$/, 'g');
const string = "${total_123}/${number_items}";

const matches = string.match(regex);

if (matches) {
  const numerator = matches[1];
  const denominator = matches[2];

  console.log("numerator:", numerator); // "total_123"
  console.log("denominator:", denominator); // "number_items"
}

The parts enclosed in parentheses in the regex pattern represent groups. These groups can be individually captured using matches array, with the elements at index 1 and 2. This allows you to capture the expressions enclosed in parentheses separately.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading