Skip to content

Commit 241650f

Browse files
committed
Push in named regexp groups as numbers
1 parent 8467056 commit 241650f

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

index.js

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@
44

55
module.exports = pathtoRegexp;
66

7+
/**
8+
* Match matching groups in a regular expression.
9+
*/
10+
var MATCHING_GROUP_REGEXP = /\((?!\?)/g;
11+
712
/**
813
* Normalize the given path string,
914
* returning a regular expression.
@@ -28,8 +33,19 @@ function pathtoRegexp(path, keys, options) {
2833
var flags = options.sensitive ? '' : 'i';
2934
var extraOffset = 0;
3035
var keysOffset = keys.length;
36+
var i = 0;
37+
var name = 0;
38+
var m;
3139

3240
if (path instanceof RegExp) {
41+
while (m = MATCHING_GROUP_REGEXP.exec(path.source)) {
42+
keys.push({
43+
name: name++,
44+
optional: false,
45+
offset: m.index
46+
});
47+
}
48+
3349
return path;
3450
}
3551

@@ -81,13 +97,8 @@ function pathtoRegexp(path, keys, options) {
8197
return '(.*)';
8298
});
8399

84-
// This is a workaround for handling *all* matching group positioning.
85-
var re = /\((?!\?)/g;
86-
var i = 0;
87-
var name = 0;
88-
var m;
89-
90-
while (m = re.exec(path)) {
100+
// This is a workaround for handling unnamed matching groups.
101+
while (m = MATCHING_GROUP_REGEXP.exec(path)) {
91102
if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) {
92103
keys.splice(keysOffset + i, 0, {
93104
name: name++, // Unnamed matching groups must be consistently linear.

test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,22 @@ describe('path-to-regexp', function () {
707707
it('should return the regexp', function () {
708708
assert.deepEqual(pathToRegExp(/.*/), /.*/);
709709
});
710+
711+
it('should pull out matching groups', function () {
712+
var params = [];
713+
var re = pathToRegExp(/(.*)/, params);
714+
var m;
715+
716+
assert.equal(params.length, 1);
717+
assert.equal(params[0].name, 0);
718+
assert.equal(params[0].optional, false);
719+
720+
m = re.exec('/route');
721+
722+
assert.equal(m.length, 2);
723+
assert.equal(m[0], '/route');
724+
assert.equal(m[1], '/route');
725+
});
710726
});
711727

712728
describe('arrays', function () {

0 commit comments

Comments
 (0)