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.
3
Answers
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.
You need to store the variables in an object, then access its properties as needed:
Also, just declare your regex using the literal syntax:
Do note that, since your regex doesn’t have a
m
flag,^
means the beginning of the string and$
the end. That being said, we can get at most one match, and theg
flag is not necessary (it even prevents us to access the groups if we use.match()
and not.matchAll()
, in fact).Try it:
First some remarks:
RegExp
constructor. Just use a regex literal.g
flag, you need a loop(?<numerator> )
Code: