Converts a re file to Regular Grammar instance
168587
def load_re_from_file(filepath):
    """"""
    regexp = None
    with open(filepath,'r') as mlfile:
        flagstr = ""
        for line in mlfile:
            cleanline = re.sub("//.*$", "", line)
            if re.search("^\s*$", cleanline):
                continue
            if re.search ("^#.*$", cleanline):
                flagstr = cleanline[1:]
                continue
            if regexp is not None:
                raise Exception("Regular expression file format error")
            else:
                regexp = cleanline.rstrip('\n')
    flags = 0
    if "i" in flagstr:
        flags |= re.I
    from pydsl.grammar.definition import RegularExpression
    return RegularExpression(regexp, flags)
832220
def load_grammar(gt="Grammar.txt", gp=None,
                 save=True, force=False, logger=None):
    """"""
    if logger is None:
        logger = logging.getLogger()
    if gp is None:
        head, tail = os.path.splitext(gt)
        if tail == ".txt":
            tail = ""
        gp = head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
    if force or not _newer(gp, gt):
        logger.info("Generating grammar tables from %s", gt)
        g = pgen.generate_grammar(gt)
        if save:
            logger.info("Writing grammar tables to %s", gp)
            try:
                g.dump(gp)
            except IOError, e:
                logger.info("Writing failed:"+str(e))
    else:
        g = grammar.Grammar()
        g.load(gp)
    return g
486132
def _make_reserved_tokens_re(reserved_tokens):
  """"""
  if not reserved_tokens:
    return None
  escaped_tokens = [_re_escape(rt) for rt in reserved_tokens]
  pattern = "(%s)" % "|".join(escaped_tokens)
  reserved_tokens_re = _re_compile(pattern)
  return reserved_tokens_re
222839
def replace(self, text):
        """"""
        for (pattern, repl) in self.patterns:
            text = re.subn(pattern, repl, text)[0]
        return text
272894
def wrap_around_re(aClass, wildcard, advice):
    
    matcher = re.compile(wildcard)
    for aMember in dir(aClass):
        realMember = getattr(aClass, aMember)
        if callable(realMember) and aMember[:6]!="__wrap" and \
           aMember[:9]!="__proceed" and \
           matcher.match(aMember):
            wrap_around(realMember, advice)
477638
def replace_wrep(t:str) -> str:
    ""
    def _replace_wrep(m:Collection[str]) -> str:
        c,cc = m.groups()
        return f' {TK_WREP} {len(cc.split())+1} {c} '
    re_wrep = re.compile(r'(\b\w+\W+)(\1{3,})')
    return re_wrep.sub(_replace_wrep, t)
1172675
def make_regex(separator):
    
    return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +
                      re.escape(separator) + r'\\]|\\.)+)')
1191714
def regex(self, *pattern, **kwargs):
        
        set_defaults(self._kwargs, kwargs)
        set_defaults(self._regex_defaults, kwargs)
        set_defaults(self._defaults, kwargs)
        pattern = self.rebulk.build_re(*pattern, **kwargs)
        part = ChainPart(self, pattern)
        self.parts.append(part)
        return part
669319
def convert_parens_in_rst_tree_str(rst_tree_str):
    '''
    
    '''
    def replace_brackets(matchobj):
        edu = matchobj.group(0)
        for (br, br_repl) in DIS_ESCAPES:
            edu = re.sub("\{}".format(br), br_repl, edu)
        return edu

    return re.sub('_!(.*?)_!', replace_brackets, rst_tree_str)
1330538
def _preprocess(argument, casesensitive):
        """"""
        pattern_set = PatternSet()
        if argument is not None:
            if isinstance(argument, STRING_TYPES):
                argument = [argument, ]

            for glob in argument:
                if isinstance(glob, str):
                    patterns = Pattern.create(glob, casesensitive)
                    pattern_set.extend(patterns)

                elif isinstance(glob, Pattern):
                    pattern_set.append(glob)

        return pattern_set
125438
def _compile_template_re(delimiters):
    
    # The possible tag type characters following the opening tag,
    # excluding "=" and "{".
    tag_types = "!>&/#^"

    # TODO: are we following this in the spec?
    #
    #   The tag's content MUST be a non-whitespace character sequence
    #   NOT containing the current closing delimiter.
    #
    tag = r"""
        (?P<whitespace>[\ \t]*)
        %(otag)s \s*
        (?:
          (?P<change>=) \s* (?P<delims>.+?)   \s* = |
          (?P<raw>{)    \s* (?P<raw_name>.+?) \s* } |
          (?P<tag>[%(tag_types)s]?)  \s* (?P<tag_key>[\s\S]+?)
        )
        \s* %(ctag)s
    """ % {'tag_types': tag_types, 'otag': re.escape(delimiters[0]), 'ctag': re.escape(delimiters[1])}

    return re.compile(tag, re.VERBOSE)
152451
def slugify(string, repchar='_'):
    
    slug_regex = re.compile(r'(^[{0}._-]+|[^a-z-A-Z0-9_.-]+|[{0}._-]+$)'.format(repchar))
    strip_regex = re.compile(r'[{0}._-]+'.format(repchar))

    transformations = [
        lambda x: slug_regex.sub(repchar, x),
        lambda x: strip_regex.sub(repchar, x),
        lambda x: x.strip(repchar),
        lambda x: x.lower(),
    ]
    result = string
    for process in transformations:
        result = process(result)

    return result
204377
def transform(self, text):
        """"""
        return re.sub(self.regex, self.repl, text)
1055211
def _compileRegExp(string, insensitive, minimal):
        
        flags = 0
        if insensitive:
            flags = re.IGNORECASE

        string = string.replace('[_[:alnum:]]', '[\\w\\d]') # ad-hoc fix for C++ parser
        string = string.replace('[:digit:]', '\\d')
        string = string.replace('[:blank:]', '\\s')

        try:
            return re.compile(string, flags)
        except (re.error, AssertionError) as ex:
            _logger.warning("Invalid pattern '%s': %s", string, str(ex))
            return None
192442
def _compile(pattern, flags):
    """"""

    return re.compile(WcParse(pattern, flags & FLAG_MASK).parse())
874788
function cloneRegExp(input) {
    'use strict';
    var pattern = input.source;
    var flags = '';
    if (input.global) {
        flags += 'g';
    }
    if (input.ignoreCase) {
        flags += 'i';
    }
    if (input.multiline) {
        flags += 'm';
    }
    return (new RegExp(pattern, flags));
}
650981
def regexp(__string: str, __pattern: str, __repl: Union[Callable, str], *,
           count: int = 0, flags: int = 0) -> str:
    
    return re.sub(__pattern, __repl, __string, count, flags)