Strip some of the ugly regexp characters from the given pattern.

    >>> normalize_route('^/user/<user_id:int>/?$')
    u'/user/(user_id:int)/'
355986
def normalize_route(route: str) -> str:
    
    normalized_route = str(route).lstrip('^').rstrip('$').rstrip('?')
    normalized_route = normalized_route.replace('<', '(').replace('>', ')')
    return normalized_route
950028
def pattern_to_regex(pattern: str) -> str:
    
    if pattern and pattern[-1] == "*":
        pattern = pattern[:-1]
        end = ""
    else:
        end = "$"
    for metac in META_CHARS:
        pattern = pattern.replace(metac, "\\" + metac)

    return "^" + VARS_PT.sub(regex_replacer, pattern) + end
943130
function regExpPrefix(re) {
    var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
    return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
  }
1363052
function normalizePath(path = '') {

  // Remove the trailing slash if one has been given
  if(path.length > 1 && path.endsWith('/')) {
    path = path.slice(0, -1);
  }

  // Remove the first slash
  if(path.startsWith('/')) {
    path = path.slice(1);
  }

  // Remove the query if it exists
  if(path.includes('?')) {
    path = path.split('?')[0];
  }

  // Decode the url
  path = decodeURIComponent(path);

  return path;
}
984004
def _simplify(self, pattern):
        # type: (str) -> str
        
        """
        # remove optional params
        # TODO(dcramer): it'd be nice to change these into [%s] but it currently
        # conflicts with the other rules because we're doing regexp matches
        # rather than parsing tokens
        result = self._optional_group_matcher.sub(lambda m: "%s" % m.group(1), pattern)

        # handle named groups first
        result = self._named_group_matcher.sub(lambda m: "{%s}" % m.group(1), result)

        # handle non-named groups
        result = self._non_named_group_matcher.sub("{var}", result)

        # handle optional params
        result = self._either_option_matcher.sub(lambda m: m.group(1), result)

        # clean up any outstanding regex-y characters.
        result = (
            result.replace("^", "")
            .replace("$", "")
            .replace("?", "")
            .replace("//", "/")
            .replace("\\", "")
        )

        return result
875989
def url_normolize(url: str):
    
    u = parse.urljoin('///{}/'.format(url), '.')
    u = re.sub(r'/+', '/', u)
    return u if url.endswith('/') else u[:-1]
783409
def reformat_pattern(pattern, compile=False):
    '''
    
    '''
    # User pattern: (w:<name>)  --> Changes to (?P<name>\w)
    rex_pattern = re.sub(r'\(w:<([\w\d_]+)>\)', '(?P<\\1>\w+)', pattern)

    # User pattern: (d:<name>)  --> change to (?P<name>\d)
    rex_pattern = re.sub(r'\(d:<([\w\d_]+)>\)', '(?P<\\1>\d+)', rex_pattern)

    # User pattern: (W:<name>)  --> change to (?P<name>\w)
    rex_pattern = re.sub(r'\(W:<([\w\d_]+)>\)', '(?P<\\1>\W+)', rex_pattern)

    # User pattern: (any:<anyvalue> --> change to (?P<anyvalue>.*)
    rex_pattern = re.sub(r'\(any:<([\w\d_]+)>\)', '(?P<\\1>.*)', rex_pattern)

    # User pattern: (ip:<ipaddr>) --> Change to (?P<ipaddr>\d+\.\d+\.\d+\.\d+)
    rex_pattern = re.sub(r'\(ip:<([\w\d_]+)>\)',
                         '(?P<\\1>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})',
                         rex_pattern)

    # User pattern: (mac:<macaddr>) --> Change to (?P<mac>\w\w:\w\w:\w\w:..)
    rex_pattern = re.sub(r'\(mac:<([\w\d_]+)>\)',
                         '(?P<\\1>\w\w:\w\w:\w\w:\w\w:\w\w:\w\w)', rex_pattern)

    # User pattern: (decimal:<name>) --> Change to (?P<name>\d*\.\d+|\d+)
    rex_pattern = re.sub(r'\(decimal:<([\w\d_]+)>\)',
                         '(?P<\\1>\d*\.\d+|\d+)', rex_pattern)

    # User pattern: (measurement:<name> --> change to \
    # (?P<name>\d*\.\d+|\d+)(\w+|\w+/\w+)
    rex_pattern = re.sub(r'\(measurement:<([\w\d_]+)>\)',
                         '(?P<\\1>\d*\.\d+|\d+)(?P<\\1_unit>\w+|\w+/\w+)',
                         rex_pattern)


    ######################################
    # Timestamp patterns.
    # User pattern: (ts[n]:<timestamp>) -->
    # Converted to: The below options.
    ######################################

    # User pattern: (ts1:<timestamp>)
    # Keystone, nova, libvirt, cinder
    # Example: 2015-11-13 06:38:04.571
    rex_pattern = re.sub(
        r'\(ts1:<([\w\d_]+)>\)',
        '(?P<\\1>(\d{4})-(\d{1,2})-(\d{1,2}) (\d+):(\d+):(\d+)\.(\d+))',
        rex_pattern)

    # User pattern: (ts2:<timestamp>)
    # contrail
    # Example: 2015-11-13 Fri 13:14:51:907.395 PST
    rex_pattern = re.sub(
        r'\(ts2:<([\w\d_]+)>\)',
        '(?P<\\1>(\d{4})-(\d{1,2})-(\d{1,2}) (\w{3}) (\d+):(\d+):(\d+):(\d+)\.(\d+))',
        rex_pattern)

    # User pattern: (ts3:<timestamp>)
    # apache2
    # Example: Thu Aug 20 14:18:34 2015
    rex_pattern = re.sub(
        r'\(ts3:<([\w\d_]+)>\)',
        '(?P<\\1>(\w{3}) (\w{3}) (\d{1,2}) (\d+):(\d+):(\d+) (\d{4}))',
        rex_pattern)

    # User pattern: (ts4:<timestamp>)
    # Example: 02/Nov/2015:09:03:19 -0800
    rex_pattern = re.sub(
        r'\(ts4:<([\w\d_]+)>\)',
        '(?P<\\1>(\d+)\/(\w{3})\/(\d{4}):(\d+):(\d+):(\d+) -(\d+))',
        rex_pattern)

    # User pattern: (ts5:<timestamp>)
    # ceph logs.
    # Example: 2015-11-13 06:25:29.436844
    rex_pattern = re.sub(
        r'\(ts5:<([\w\d_]+)>\)',
        '(?P<\\1>(\d{4})-(\d{1,2})-(\d{1,2}) (\d+):(\d+):(\d+)\.(\d+))',
        rex_pattern)

    # User pattern: (ts6:<timestamp>)
    # cassandra
    # Example:2015-10-23 12:38:15
    rex_pattern = re.sub(
        r'\(ts6:<([\w\d_]+)>\)',
        '(?P<\\1>(\d{4})-(\d{1,2})-(\d{1,2}) (\d+):(\d+):(\d+))',
        rex_pattern)

    # User pattern: (ts7:<timestamp>)
    # haproxy
    # Example: 13/Nov/2015:06:25:05.465
    rex_pattern = re.sub(
        r'\(ts7:<([\w\d_]+)>\)',
        '(?P<\\1>(\d+)\/(\w{3})\/(\d{4}):(\d+):(\d+):(\d+)\.(\d+))',
        rex_pattern)

    # User pattern: (ts8:<timestamp>)
    # mysql
    # Example: 12:03:28
    rex_pattern = re.sub(
        r'\(ts8:<([\w\d_]+)>\)',
        '(?P<\\1>(\d+):(\d+):(\d+))',
        rex_pattern)

    # User pattern: (ts9:<timestamp>)
    # reddis
    # Example: 08 Nov 06:26:05.084
    rex_pattern = re.sub(
        r'\(ts9:<([\w\d_]+)>\)',
        '(?P<\\1>(\d+) (\w{3}) (\d+):(\d+):(\d+)\.(\d+))',
        rex_pattern)

    # user pattern: (ts10:<timestamp>)
    # supervisord, zookeeper
    # Example: 2015-06-30 10:59:18,133
    rex_pattern = re.sub(
        r'\(ts10:<([\w\d_]+)>\)',
        '(?P<\\1>(\d{4})-(\d{1,2})-(\d{1,2}) (\d+):(\d+):(\d+),(\d+))',
        rex_pattern)

    # User pattern: (ts11:<timestamp>)
    # dmesg
    # Example: 11148214.574583
    rex_pattern = re.sub(
        r'\(ts11:<([\w\d_]+)>\)',
        '(?P<\\1>(\d+)\.(\d+))',
        rex_pattern)

    # Finally if no prefix is specified take default action.
    rex_pattern = re.sub(r'\(<([\w\d_]+)>\)', '(?P<\\1>.*)', rex_pattern)

    if compile:
        return re.compile(rex_pattern)

    return rex_pattern
718761
private static String convertPattern(ProxyRule bean) {
        String str = bean.getPattern().replaceAll("\\{.+?\\}", "([^/&?]*)"); // /foo/{bar}/{baz} => /foo/([^\/&?]*)/([^/&?]*).*
        return str.endsWith("$") ? str : str + ".*";  // Implicitly other stuff on end unless $ explicitly specified (see description)
    }
818284
def normaliseURL(url):
    
    url = unicode_safe(url).strip()
    # XXX: brutal hack
    url = unescape(url)

    pu = list(urlparse(url))
    segments = pu[2].split('/')
    while segments and segments[0] in ('', '..'):
        del segments[0]
    pu[2] = '/' + '/'.join(segments)
    # remove leading '&' from query
    if pu[4].startswith('&'):
        pu[4] = pu[4][1:]
    # remove anchor
    pu[5] = ""
    return urlunparse(pu)
509854
function normalizeSeparators (p) {
  p = p || "";

  if (path.sep === "\\") {
    // Replace backslashes with forward slashes
    return p.replace(/\\/g, "/");
  }
  else {
    // Return the path as-is, since it should already have proper URL separators.
    // If it DOES contain backslashes, then they are treated as normal characters,
    // NOT as separators
    return p;
  }
}
992209
def _escape_regexp(s):
    """"""
    return (
        str(s)
        .replace('|', '\\|')
        .replace('.', '\.')  # `.` has to be replaced before `*`
        .replace('*', '.*')
        .replace('+', '\+')
        .replace('(', '\(')
        .replace(')', '\)')
        .replace('$', '\\$')
    )
1066123
def strip_escape(string='', encoding="utf-8"):  # pylint: disable=redefined-outer-name
    
    matches = []
    try:
        if hasattr(string, "decode"):
            string = string.decode(encoding)
    except Exception: # pylint: disable=broad-except
        # Tried to decode something that is not decodeable in the specified encoding. Let's just
        # move on.
        pass
    try:
        for match in ansi_eng.finditer(string):
            matches.append(match)
    except TypeError as error:
        raise TypeError("Unable to strip escape characters from data {}: {}".format(
            string, error))
    matches.reverse()
    for match in matches:
        start = match.start()
        end = match.end()
        string = string[0:start] + string[end:]
    return string
1142475
def uri_to_regexp(self, uri):
        
        def _convert(elem, is_last):
            if not re.match('^{.*}$', elem):
                return elem
            name = elem.replace('{', '').replace('}', '')
            if is_last:
                return '(?P<%s>[^/]*)' % name
            return '(?P<%s>.*)' % name

        elems = uri.split('/')
        num_elems = len(elems)
        regexp = '^{}$'.format('/'.join([_convert(elem, (i == num_elems - 1)) for i, elem in enumerate(elems)]))
        return regexp
1124817
def startswith_strip(s, startswith='http://', ignorecase=True):
    
    if ignorecase:
        if s.lower().startswith(startswith.lower()):
            return s[len(startswith):]
    else:
        if s.endswith(startswith):
            return s[len(startswith):]
    return s
348857
def slugify(value):
    
    value = re.sub(r"[^\w\s-]", "", value).strip()
    return re.sub(r"[-\s]+", "-", value)
1164730
def strip_path_session_id(path):
    ''''''
    for pattern in SESSION_ID_PATH_PATTERNS:
        match = pattern.match(path)
        if match:
            path = match.group(1) + match.group(3)

    return path
1254243
def slugify(value, allow_dots=False, allow_unicode=False):
    
    if allow_dots:
        pattern = _re_pattern_allow_dots
    else:
        pattern = _re_pattern

    value = six.text_type(value)
    if allow_unicode:
        value = unicodedata.normalize('NFKC', value)
        value = pattern.sub('', value).strip().lower()
        return _re_spaces.sub('-', value)
    value = unicodedata.normalize('NFKD', value).encode(
        'ascii', 'ignore').decode('ascii')
    value = pattern.sub('', value).strip().lower()
    return _re_spaces.sub('-', value)