2 * Expose `pathtoRegexp`.
5 module.exports = pathtoRegexp;
8 * Match matching groups in a regular expression.
10 var MATCHING_GROUP_REGEXP = /\((?!\?)/g;
13 * Normalize the given path string,
14 * returning a regular expression.
16 * An empty array should be passed,
17 * which will contain the placeholder
18 * key names. For example "/user/:id" will
19 * then contain ["id"].
21 * @param {String|RegExp|Array} path
23 * @param {Object} options
28 function pathtoRegexp(path, keys, options) {
29 options = options || {};
31 var strict = options.strict;
32 var end = options.end !== false;
33 var flags = options.sensitive ? '' : 'i';
35 var keysOffset = keys.length;
40 if (path instanceof RegExp) {
41 while (m = MATCHING_GROUP_REGEXP.exec(path.source)) {
52 if (Array.isArray(path)) {
53 // Map array parts into regexps and return their source. We also pass
54 // the same keys and options instance into every generation to get
55 // consistent matching groups before we join the sources together.
56 path = path.map(function (value) {
57 return pathtoRegexp(value, keys, options).source;
60 return new RegExp('(?:' + path.join('|') + ')', flags);
63 path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?'))
64 .replace(/\/\(/g, '/(?:')
65 .replace(/([\/\.])/g, '\\$1')
66 .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional, offset) {
68 format = format || '';
69 capture = capture || '([^\\/' + format + ']+?)';
70 optional = optional || '';
75 offset: offset + extraOffset
79 + (optional ? '' : slash)
81 + format + (optional ? slash : '') + capture
82 + (star ? '((?:[\\/' + format + '].+?)?)' : '')
86 extraOffset += result.length - match.length;
90 .replace(/\*/g, function (star, index) {
93 while (len-- > keysOffset && keys[len].offset > index) {
94 keys[len].offset += 3; // Replacement length minus asterisk length.
100 // This is a workaround for handling unnamed matching groups.
101 while (m = MATCHING_GROUP_REGEXP.exec(path)) {
105 while (path.charAt(--index) === '\\') {
109 // It's possible to escape the bracket.
110 if (escapeCount % 2 === 1) {
114 if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) {
115 keys.splice(keysOffset + i, 0, {
116 name: name++, // Unnamed matching groups must be consistently linear.
125 // If the path is non-ending, match until the end or a slash.
126 path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)'));
128 return new RegExp(path, flags);