I need to match an expression and extract values from it using named groups.
Lets say this is my string:
var str = 'element=123'
So i want to match it using regex and extract the element and value.
I know how to do it is c#, I am trying to figure it out in JS.
This is my regex:
new RegExp(/^(<element>[A-Za-z0-9])+=[A-Za-z0-9]+$/);
What am I doing wrong?
Mixing named and numbered capturing groups is not recommended because flavors are inconsistent in how the groups are numbered. If a group doesn't need to have a name, make it non-capturing using the (?:group) syntax.
A part of a pattern can be enclosed in parentheses (...) . This is called a “capturing group”. That has two effects: It allows to get a part of the match as a separate item in the result array.
Named capturing group: Matches "x" and stores it on the groups property of the returned matches under the name specified by <Name> . The angle brackets ( < and > ) are required for group name.
Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".
Now, with ES2018, RegExp named capture groups are actually possible.
Here's an example already working in Chrome 64 (soon to be available also in Safari).
const isoDateExpression = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
let match = isoDateExpression.exec('1999-12-31');
console.log(
match.groups.year, // 1999
match.groups.month, // 12
match.groups.day, // 31
)
Syntax reference: https://github.com/tc39/proposal-regexp-named-groups
Firefox haven't decided yet, but here's an entry in Mozilla's issue tracker:
https://bugzilla.mozilla.org/show_bug.cgi?id=1362154
Edit: Named capture groups are now implemented in major browsers and available since Chrome 62 (2018), Firefox 78 (2020) and Safari 11.3 (2018).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With