Skip to content

Commit 114f62d

Browse files
Add support for named matching groups (#301)
1 parent 039118d commit 114f62d

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

index.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ module.exports = pathtoRegexp;
77
/**
88
* Match matching groups in a regular expression.
99
*/
10-
var MATCHING_GROUP_REGEXP = /\((?!\?)/g;
10+
var MATCHING_GROUP_REGEXP = /\((?:\?<(.*?)>)?(?!\?)/g;
1111

1212
/**
1313
* Normalize the given path string,
@@ -40,7 +40,7 @@ function pathtoRegexp(path, keys, options) {
4040
if (path instanceof RegExp) {
4141
while (m = MATCHING_GROUP_REGEXP.exec(path.source)) {
4242
keys.push({
43-
name: name++,
43+
name: m[1] || name++,
4444
optional: false,
4545
offset: m.index
4646
});

test.js

+25
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,7 @@ describe('path-to-regexp', function () {
574574
it('should match trailing slashing in non-ending strict mode', function () {
575575
var params = [];
576576
var re = pathToRegExp('/route/', params, { end: false, strict: true });
577+
var m;
577578

578579
assert.equal(params.length, 0);
579580

@@ -600,6 +601,7 @@ describe('path-to-regexp', function () {
600601
it('should not match trailing slashes in non-ending strict mode', function () {
601602
var params = [];
602603
var re = pathToRegExp('/route', params, { end: false, strict: true });
604+
var m;
603605

604606
assert.equal(params.length, 0);
605607

@@ -617,6 +619,7 @@ describe('path-to-regexp', function () {
617619
it('should match text after an express param', function () {
618620
var params = [];
619621
var re = pathToRegExp('/(:test)route', params);
622+
var m;
620623

621624
assert.equal(params.length, 1);
622625
assert.equal(params[0].name, 'test');
@@ -723,6 +726,28 @@ describe('path-to-regexp', function () {
723726
assert.equal(m[0], '/route');
724727
assert.equal(m[1], '/route');
725728
});
729+
730+
it('should pull out matching named groups', function () {
731+
var params = [];
732+
var re = pathToRegExp(/\/(.*)\/(?<foo>.*)\/(.*)/, params);
733+
var m;
734+
735+
assert.equal(params.length, 3);
736+
assert.equal(params[0].name, 0);
737+
assert.equal(params[0].optional, false);
738+
assert.equal(params[1].name, 'foo');
739+
assert.equal(params[1].optional, false);
740+
assert.equal(params[2].name, 1);
741+
assert.equal(params[2].optional, false);
742+
743+
m = re.exec('/foo/bar/baz');
744+
745+
assert.equal(m.length, 4);
746+
assert.equal(m[0], '/foo/bar/baz');
747+
assert.equal(m[1], 'foo');
748+
assert.equal(m[2], 'bar');
749+
assert.equal(m[3], 'baz');
750+
})
726751
});
727752

728753
describe('arrays', function () {

0 commit comments

Comments
 (0)