12

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?

zx81
  • 41,100
  • 9
  • 89
  • 105
user3770158
  • 379
  • 1
  • 5
  • 16
  • 2
    http://stackoverflow.com/questions/5367369/named-capturing-groups-in-javascript-regex – trainoasis Jul 21 '14 at 07:00
  • If you have a set pattern on the string 'str', then you can use slit by ('=') to read key and value separately. e.g. str.split('=')[0] , str.split('=')[1]; , Just an short method if you want to avoid Regex. – foo-baar Jul 21 '14 at 07:02

2 Answers2

35

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).

Nux
  • 9,276
  • 5
  • 59
  • 72
6

JavaScript does not support named capture groups.

You will have to use numbered groups.

For instance:

var myregex = /([^=]+)=(.*)/;
var matchArray = myregex.exec(yourString);
if (matchArray != null) {
    element = matchArray[1];
    id = matchArray[2];

} 

Option 2: XRegExp

The alternate regex library for JavaScript XregexP supports named captures as well as other important regex features missing from JS regex, such as lookbehinds.

Elad Nava
  • 7,746
  • 2
  • 41
  • 61
zx81
  • 41,100
  • 9
  • 89
  • 105
  • 15
    obsolete answer. – Giorgio Robino May 30 '19 at 11:46
  • no it's not obsolete - a lot of major browsers still do not support named capture groups even though JS technically does. – sevenseacat Jun 04 '19 at 07:36
  • 1
    Yes, it is obsolete. The JavaScript language supports named capture groups, even if some browsers don't. Currently, only IE fails to support this. See the compatibility chart at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp – Corey Aug 21 '21 at 17:02
  • 2
    If it wasn't then it is now: https://caniuse.com/?search=named%20capture – wils Jul 02 '22 at 19:39