named-regexp-groups
Regular expressions with named capture groups and named back-references
Create a named capture group with (?<name>.*)
or (:<name>.*)
when using
a RegExp. The methods of RegExp are supported excluding compile and toString.
Use named back-references using (?&name)
to include already defined named pattern.
Installation
npm install --save named-regexp-groups
Usage
import NamedRegExp from 'named-regexp-groups'
const NamedRegExp = require('named-regexp-groups')
var r = new NamedRegExp('(?<foo>foo)(?<bar>)(-)(?:wat)(?<na>(?:na)+)(?&na)')
var r = new NamedRegExp(/(:<foo>foo)(:<bar>)(-)(?:wat)(:<na>(?:na)+)(:&na)/)
r.source
For nodejs < v5.0 core-js
polyfills are required.
Use npm i -S core-js
in your project and add:
require('core-js/es6/object')
require('core-js/es6/string')
require('core-js/es6/symbol')
exec
var r = new NamedRegExp('(?<foo>foo)(?<bar>bar)(-)(?:wat)(?<na>(?:na)+)(?&na)')
r.exec('nanafoobar-watnana')
test
r = new NamedRegExp('(?<foo>foo)(bar)(?:waah)')
r.source
r.test('nanafoobarwaah')
String.replace
If using a string as replacement use $+{name}
to define the placeholder for the capture group.
This follows the Syntax of PCRE Named backreferences.
var r = new NamedRegExp(/(:<year>\d+)-(:<month>\d+)-(:<day>\d+)/)
'2017-01-02'.replace(r, 'day: $+{day}, month: $+{month}, year: $+{year}')
'2016-11-22'.replace(r, function () {
var args = [].slice.call(arguments)
var g = this.groups
return `day: ${args[g.day]}, month: ${args[g.month]}, year: ${args[g.year]}`
})
String.match
r = new NamedRegExp('(?<foo>foo)(bar)(?:waah)')
'nanafoobarwaah'.match(r)
String.split
r = new NamedRegExp('(?<foo>foo)')
'nanafoobarwaah'.split(r)
ES7
The proposed TC39 proposal-regexp-named-groups is finding it's way into the standard.
Chrome>=64 already supports named groups. Maybe node>=10 soon as well...
Paste this into Chrome>=64
r = new RegExp(/(?<foo>foo)(?<bar>bar)(-)(?:wat)(?<na>(?:na)+)/);
o = r.exec('nanafoobar-watnana')
License
Software is released under MIT.