2 * Expose `pathtoRegexp`.
5 module.exports = pathtoRegexp;
8 * Normalize the given path string,
9 * returning a regular expression.
11 * An empty array should be passed,
12 * which will contain the placeholder
13 * key names. For example "/user/:id" will
14 * then contain ["id"].
16 * @param {String|RegExp|Array} path
18 * @param {Object} options
23 function pathtoRegexp(path, keys, options) {
24 options = options || {};
25 var strict = options.strict;
26 var end = options.end !== false;
27 var flags = options.sensitive ? '' : 'i';
30 if (path instanceof RegExp) {
34 if (Array.isArray(path)) {
35 // Map array parts into regexps and return their source. We also pass
36 // the same keys and options instance into every generation to get
37 // consistent matching groups before we join the sources together.
38 path = path.map(function (value) {
39 return pathtoRegexp(value, keys, options).source;
42 return new RegExp('(?:' + path.join('|') + ')', flags);
45 path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?'))
46 .replace(/\/\(/g, '/(?:')
47 .replace(/([\/\.])/g, '\\$1')
48 .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional) {
50 format = format || '';
51 capture = capture || '([^\\/' + format + ']+?)';
52 optional = optional || '';
54 keys.push({ name: key, optional: !!optional });
57 + (optional ? '' : slash)
59 + format + (optional ? slash : '') + capture
60 + (star ? '((?:[\\/' + format + '].+?)?)' : '')
64 .replace(/\*/g, '(.*)');
66 // If the path is non-ending, match until the end or a slash.
67 path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)'));
69 return new RegExp(path, flags);