Skip to content

Commit

Permalink
Add support for named matching groups (#301)
Browse files Browse the repository at this point in the history
  • Loading branch information
NorbertSzydlik authored Apr 7, 2024
1 parent 039118d commit 114f62d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module.exports = pathtoRegexp;
/**
* Match matching groups in a regular expression.
*/
var MATCHING_GROUP_REGEXP = /\((?!\?)/g;
var MATCHING_GROUP_REGEXP = /\((?:\?<(.*?)>)?(?!\?)/g;

/**
* Normalize the given path string,
Expand Down Expand Up @@ -40,7 +40,7 @@ function pathtoRegexp(path, keys, options) {
if (path instanceof RegExp) {
while (m = MATCHING_GROUP_REGEXP.exec(path.source)) {
keys.push({
name: name++,
name: m[1] || name++,
optional: false,
offset: m.index
});
Expand Down
25 changes: 25 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,7 @@ describe('path-to-regexp', function () {
it('should match trailing slashing in non-ending strict mode', function () {
var params = [];
var re = pathToRegExp('/route/', params, { end: false, strict: true });
var m;

assert.equal(params.length, 0);

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

assert.equal(params.length, 0);

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

assert.equal(params.length, 1);
assert.equal(params[0].name, 'test');
Expand Down Expand Up @@ -723,6 +726,28 @@ describe('path-to-regexp', function () {
assert.equal(m[0], '/route');
assert.equal(m[1], '/route');
});

it('should pull out matching named groups', function () {
var params = [];
var re = pathToRegExp(/\/(.*)\/(?<foo>.*)\/(.*)/, params);
var m;

assert.equal(params.length, 3);
assert.equal(params[0].name, 0);
assert.equal(params[0].optional, false);
assert.equal(params[1].name, 'foo');
assert.equal(params[1].optional, false);
assert.equal(params[2].name, 1);
assert.equal(params[2].optional, false);

m = re.exec('/foo/bar/baz');

assert.equal(m.length, 4);
assert.equal(m[0], '/foo/bar/baz');
assert.equal(m[1], 'foo');
assert.equal(m[2], 'bar');
assert.equal(m[3], 'baz');
})
});

describe('arrays', function () {
Expand Down

0 comments on commit 114f62d

Please sign in to comment.