Compile route matcher into regexp.
508600
private function compile()
    {
        $options = $replaces = [];
        $pattern = rtrim(ltrim($this->pattern, ':/'), '/');

        // correct [/ first occurrence]
        if (strpos($pattern, '[/') === 0) {
            $pattern = '[' . substr($pattern, 2);
        }

        if (preg_match_all('/<(\w+):?(.*?)?>/', $pattern, $matches)) {
            $variables = array_combine($matches[1], $matches[2]);

            foreach ($variables as $key => $segment) {
                $segment = $this->prepareSegment($key, $segment);
                $replaces["<$key>"] = "(?P<$key>$segment)";
                $options[] = $key;
            }
        }

        $template = preg_replace('/<(\w+):?.*?>/', '<\1>', $pattern);
        $options = array_fill_keys($options, null);

        foreach ($this->constrains as $key => $value) {
            if ($value instanceof Autofill) {
                // only forces value replacement, not required to be presented as parameter
                continue;
            }

            if (!array_key_exists($key, $options)) {
                throw new ConstrainException(sprintf(
                    "Route `%s` does not define routing parameter `<%s>`.",
                    $this->pattern,
                    $key
                ));
            }
        }

        $this->compiled = '/^' . strtr($template, $replaces + self::PATTERN_REPLACES) . '$/iu';
        $this->template = stripslashes(str_replace('?', '', $template));
        $this->options = $options;
    }
5046
protected function compileRoute($route)
    {
        // First escape all of the non-named param (non [block]s) for regex-chars
        $route = preg_replace_callback(
            static::ROUTE_ESCAPE_REGEX,
            function ($match) {
                return preg_quote($match[0]);
            },
            $route
        );

        // Get a local reference of the match types to pass into our closure
        $match_types = $this->match_types;

        // Now let's actually compile the path
        $route = preg_replace_callback(
            static::ROUTE_COMPILE_REGEX,
            function ($match) use ($match_types) {
                list(, $pre, $type, $param, $optional) = $match;

                if (isset($match_types[$type])) {
                    $type = $match_types[$type];
                }

                // Older versions of PCRE require the 'P' in (?P<named>)
                $pattern = '(?:'
                         . ($pre !== '' ? $pre : null)
                         . '('
                         . ($param !== '' ? "?P<$param>" : null)
                         . $type
                         . '))'
                         . ($optional !== '' ? '?' : null);

                return $pattern;
            },
            $route
        );

        $regex = "`^$route$`";

        // Check if our regular expression is valid
        $this->validateRegularExpression($regex);

        return $regex;
    }
167694
def build_regex(self, tokens):
        """"""
        patterns = []
        for token in tokens:
            patterns.append(token.pattern_start)
            if token.pattern_end:
                patterns.append(token.pattern_end)
        return re.compile('|'.join(patterns), re.DOTALL)
441684
function compileStringRouteExpression (routeExpression) {
  var routeUri = new URI(routeExpression);
  routeUri.path = module.exports.removeEndSlash(routeUri.path);
  if (!routeUri) {
    return null;
  }

  // escape regular expression characters
  var escaped = routeUri.path.replace(
    EXPRESSION_ESCAPE_REG_EXP, '\\$&'
  );

  // get all occurrences of routing parameters in URI path
  var regExpSource = '^' + escaped.replace(PARAMETER_REG_EXP, URI_PATH_REPLACEMENT_REG_EXP_SOURCE) + '$';
  var expression = new RegExp(regExpSource, 'i');
  var pathParameterMatches = escaped.match(PARAMETER_REG_EXP);
  var pathParameters = pathParameterMatches ? pathParameterMatches.map(getParameterDescriptor) : null;

  var pathMapper = pathParameters ? createUriPathMapper(expression, pathParameters) : null;
  var queryMapper = routeUri.query ? createUriQueryMapper(routeUri.query) : null;

  return {
    expression: expression,
    map: uri => {
      var args = Object.create(null);

      if (pathMapper) {
        pathMapper(uri.path, args);
      }

      if (queryMapper && uri.query) {
        queryMapper(uri.query.values, args);
      }

      return args;
    }
  };
}
159928
public RouteMatcher allWithRegEx(String regex, Handler<HttpServerRequest> handler) {
		addRegEx(regex, handler, getBindings);
		addRegEx(regex, handler, putBindings);
		addRegEx(regex, handler, postBindings);
		addRegEx(regex, handler, deleteBindings);
		addRegEx(regex, handler, optionsBindings);
		addRegEx(regex, handler, headBindings);
		addRegEx(regex, handler, traceBindings);
		addRegEx(regex, handler, connectBindings);
		addRegEx(regex, handler, patchBindings);
		return this;
	}
184467
function(request, urlVar, urlVal, params) {

        var matched     = -1
            , _param    = urlVar.match(/\:\w+/g)
            , regex     = null
            , tested    = false;

        if (!_param.length) return false;

        //  if custom path, path rewrite
        if (request.routing.param.path) {
            regex = new RegExp(urlVar, 'g')
            if ( regex.test(request.routing.param.path) ) {
                request.routing.param.path = request.routing.param.path.replace(regex, urlVal);
            }
        }

        //  if custom file, file rewrite
        if (request.routing.param.file) {
            regex = new RegExp(urlVar, 'g')
            if ( regex.test(request.routing.param.file) ) {
                request.routing.param.file = request.routing.param.file.replace(regex, urlVal);
            }
        }

        if (_param.length == 1) {// fast one
            matched =  ( _param.indexOf(urlVar) > -1 ) ? _param.indexOf(urlVar) : false;

            if (matched === false) return matched;
            // filter on method
            if (params.method !== request.method) return false;

            var key = _param[matched].substr(1);
            regex   = params.requirements[key];

            if ( /^\//.test(regex) ) {
                var re      = regex.match(/\/(.*)\//).pop()
                    , flags = regex.replace('/'+ re +'/', '');

                tested = new RegExp(re, flags).test( urlVal )

            } else {
                tested = new RegExp(params.requirements[key]).test( urlVal )
            }

            if (
                typeof(params.param[key]) != 'undefined' &&
                typeof(params.requirements) != 'undefined' &&
                typeof(params.requirements[key]) != 'undefined' &&
                tested
            ) {
                request.params[key] = urlVal;
                return true
            }

        } else { // slow one

            // In order to support rules defined like :
            //      { params.url }  => `/section/:name/page:number`
            //      { request.url } => `/section/plante/page4`
            //
            //      with keys = [ ":name", ":number" ]

            var keys        = _param
                , tplUrl    = params.url
                , url       = request.url
                , values    = {}
                , strVal    = ''
                , started   = false
                , i         = 0;

            for (var c = 0, posLen = url.length; c < posLen; ++c) {
                if (url.charAt(c) == tplUrl.charAt(i) && !started) {
                    ++i
                    continue
                } else if (strVal == '') { // start

                    started = true;
                    strVal += url.charAt(c);
                } else if ( c > (tplUrl.indexOf(keys[0]) + keys[0].length) ) {

                    regex   = params.requirements[keys[0]];
                    urlVal  = strVal.substr(0, strVal.length);

                    if ( /^\//.test(regex) ) {
                        var re      = regex.match(/\/(.*)\//).pop()
                            , flags = regex.replace('/'+ re +'/', '');

                        tested = new RegExp(re, flags).test( urlVal )

                    } else {
                        tested = new RegExp(params.requirements[key]).test( urlVal )
                    }

                    if (tested) {
                        values[ keys[0].substr(1) ] = urlVal
                    } else {
                        return false
                    }

                    strVal =  '';
                    started = false;
                    i = (tplUrl.indexOf(keys[0]) + keys[0].length);
                    c -= 1;

                    keys.splice(0,1)
                } else {
                    strVal += url.charAt(c);
                    ++i
                }

                if (c == posLen - 1 ) {

                    regex   = params.requirements[keys[0]];
                    urlVal  = strVal.substr(0, strVal.length);

                    if ( /^\//.test(regex) ) {
                        var re      = regex.match(/\/(.*)\//).pop()
                            , flags = regex.replace('/'+ re +'/', '');

                        tested = new RegExp(re, flags).test( urlVal )

                    } else {
                        tested = new RegExp(params.requirements[key]).test( urlVal )
                    }

                    if (tested) {
                        values[ keys[0].substr(1) ] = urlVal
                    } else {
                        return false
                    }

                }

            }

            if (values.count() == keys.length) {
                for (var key in values) {
                    request.params[key] = values[key];
                }
                return true
            }

        }

        return false
    }
460365
function PathPattern(options) {
    // The route string are compiled to a regexp (if it isn't already)
    this.regexp = options.regexp;

    // The query parameters specified in the path part of the route
    this.params = options.params;

    // The original routestring (optional)
    this.routeString = options.routeString;
  }
748438
def file_matches_regexps(filename, patterns):
    """"""
    return any(re.match(pat, filename) for pat in patterns)
492986
function(route) 
	{
		var rootStripper 	= /^\/+|\/+$/g;
		var optionalParam 	= /\((.*?)\)/g;
		var namedParam		= /(\(\?)?:\w+/g;
		var splatParam		= /\*\w+/g;
		var escapeRegExp	= /[\-{}\[\]+?.,\\\^$|#\s]/g;
		
		route = route
			.replace(rootStripper, '')
			.replace(escapeRegExp, '\\$&')
			.replace(optionalParam, '(?:$1)?')
			.replace(namedParam, function(match, optional)
			{
				return optional ? match : '([^\/]+)';
			})
			.replace(splatParam, '(.*?)');
		
		return new RegExp('^' + route + '$');
	}
1359026
def sinatra_path_to_regex(cls, path):
        
        # Return the path if already a (compiled) regex
        if type(path) is cls.regex_type:
            return path

        # Build a regular expression string which is split on the '/' character
        regex = [
            "(?P<{}>\w+)".format(segment[1:])
            if cls.sinatra_param_regex.match(segment)
            else segment
            for segment in path.split('/')
        ]
        return re.compile('/'.join(regex))
1271809
def _match(self, regex):
        """"""
        cregex = re.compile(regex)
        for line in self.content.splitlines():
            match = cregex.match(line)
            if match:
                return match
        raise Exception('No "{0}" line in {1}.cpp'.format(
            regex_to_error_msg(regex),
            self.name
        ))
1091548
function extractParams(route, path) {
    var vals = route.regex.exec(path).slice(1), params = {}, i, n;

    for (i = 0, n = route.names.length; i < n; i++) {
      params[route.names[i]] = vals[i];
    }

    return params;
  }
273309
def setup_regex(self):
        """"""
        self._RX_INTERFACE = (r"\n\s*interface\s+(?P<name>[a-z0-9_]+)(\s\((?P<symbol>[.\w+*=/-]+)\))?"
                              r"(?P<contents>.+?)"
                              r"end\s*interface\s+(?P=name)?")
        self.RE_INTERFACE = re.compile(self._RX_INTERFACE, re.I | re.DOTALL)
1325790
def _make_regex(self):
        
        rxp = "|".join(
            map(self._address_rxp, self.keys()),
        )
        self._regex = re.compile(
            rxp,
            re.IGNORECASE,
        )
869907
public static function compile(Route $route)
    {
        $staticPrefix = false;
        $variables = [];
        $pos = 0;
        $extractedRegexes = [];
        $defaults = [];

        // set correct static prefix
        $prefix = $route->getHost() == '' ? '' : $route->getHost() . '/';

        // route regex
        $routePatternObject = self::str($route->getPath())->trimLeft('/');

        // if path is empty
        // e.g. the path is empty if you are matching a start page
        if($routePatternObject->val()==''){
            return new CompiledRoute(false, false, [], [], false);
        }

        $routePattern = $prefix . $routePatternObject->val() . '$';

        // we append the regex to match the string from beginning only if the path starts with http or '/'
        if($routePatternObject->startsWith('http')) {
            $routePattern = '^' . $routePattern;
        }else if(self::str($route->getRealPath())->startsWith('/') && self::str($route->getRealPath())->length()>1){
            $routePattern = '^/' . $routePattern;
        }
        // set regex delimiters
        $routePattern = '#' . $routePattern . '#';

        // extract all variables
        preg_match_all('#\{\w+\}#', $route->getPath(), $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
        foreach ($matches as $m) {
            $var = substr($m[0][0], 1, -1);

            // get all the text before the variable
            if(!$staticPrefix) {
                $prefix = substr($route->getPath(), $pos, ($m[0][1] - $pos));
                $pos = $m[0][1] + strlen($m[0][0]);
                $precedingChar = strlen($prefix) > 0 ? substr($prefix, -1) : '';
                if(strlen($precedingChar) === 1 && strpos(self::SEPARATORS, $precedingChar) !== false) {
                    $staticPrefix .= substr($prefix, 0, -1);
                } else {
                    $staticPrefix .= $prefix;
                }
            }

            $regex = '[\w-]+';
            $default = false;
            if($route->hasOption($var)) {
                // pattern
                if($route->getOptions()[$var]->hasAttribute('Pattern')) {
                    $regex = $route->getOptions()[$var]->getAttribute('Pattern');
                }

                // default
                if($route->getOptions()[$var]->hasAttribute('Default')) {
                    $default = $route->getOptions()[$var]->getAttribute('Default');
                }
            }
            $extractedRegexes[$var] = $regex;
            $defaults['{' . $var . '}'] = $default;

            $variables[] = ['name' => $var];
            $routePattern = str_replace($m[0][0], '(' . $regex . ')', $routePattern);
        }

        // build the default route
        $defaultRoute = false;
        if(count($defaults) > 0) {
            $defaultRoute = str_replace(array_keys($defaults), array_values($defaults), $route->getPath());
        }

        return new CompiledRoute($staticPrefix, $routePattern, $variables, $extractedRegexes, $defaultRoute);
    }
660731
private boolean matchesPath(String routePath, String pathToMatch) {
		routePath = routePath.replaceAll(Path.VAR_REGEXP, Path.VAR_REPLACE);
		return pathToMatch.matches("(?i)" + routePath);
	}
131634
protected function buildRegexp($pattern, array $matches)
    {
        $src = [];
        $trg = [];
        foreach ($matches as $match) {
            list($key, $regexp) = $this->splitSegment($match[3]);

            if (in_array(substr($regexp, -1), ['+', '*', '?'])) {
                throw new RouteException('Route must not end with quantification token');
            }

            $src[rtrim($match[0], '/')] = $key;

            $trg[$key] = '(?P<' . $key . '>' . $regexp . '+)';

            if ($match[1] == '(') {
                $trg[$key] = '(' . $trg[$key] . $this->buildConditionalSlash(preg_quote($match[4], '/')) . ')?';
            }
        }

        $pattern = strtr($pattern, $src);
        $pattern = preg_quote($pattern, '/');
        $pattern = strtr($pattern, $trg);
        $pattern = str_replace('\/((?P', '\/?((?P', $pattern);
        $pattern = $this->buildConditionalSlash($pattern);

        return '/^' . $pattern . '$/i';
    }