Build a compiled regex object.
545107
def get_units_regex():
    """"""
    op_keys = sorted(OPERATORS.keys(), key=len, reverse=True)
    unit_keys = sorted(l.UNITS.keys(), key=len, reverse=True)
    symbol_keys = sorted(l.SYMBOLS.keys(), key=len, reverse=True)

    exponent = ur'(?:(?:\^?\-?[0-9%s]*)(?:\ cubed|\ squared)?)(?![a-zA-Z])' % \
               SUPERSCRIPTS

    all_ops = '|'.join([r'%s' % re.escape(i) for i in op_keys])
    all_units = '|'.join([ur'%s' % re.escape(i) for i in unit_keys])
    all_symbols = '|'.join([ur'%s' % re.escape(i) for i in symbol_keys])

    pattern = ur'''

        (?P<prefix>(?:%s)(?![a-zA-Z]))?         # Currencies, mainly
        (?P<value>%s)-?                           # Number
        (?:(?P<operator1>%s)?(?P<unit1>(?:%s)%s)?)    # Operator + Unit (1)
        (?:(?P<operator2>%s)?(?P<unit2>(?:%s)%s)?)    # Operator + Unit (2)
        (?:(?P<operator3>%s)?(?P<unit3>(?:%s)%s)?)    # Operator + Unit (3)
        (?:(?P<operator4>%s)?(?P<unit4>(?:%s)%s)?)    # Operator + Unit (4)

    ''' % tuple([all_symbols, RAN_PATTERN] + 4 * [all_ops, all_units,
                                                  exponent])

    regex = re.compile(pattern, re.VERBOSE | re.IGNORECASE)

    return regex
1034685
function regExpBuilder (find) {
  const regExpRe = /\/(.*)\/(\w*)/
  if (find) {
    if (regExpRe.test(find)) {
      const matches = find.match(regExpRe)
      const pattern = matches[1]
      const flags = matches[2]
      return new RegExp(pattern, flags)
    } else {
      return find
    }
  } else {
    return null
  }
}
418649
def _generate_regex(self, line):
        '''
        
        '''
        restr = ""

        # Strings and single byte signatures are taken at face value;
        # multi-byte integer values are turned into regex strings based
        # on their data type size and endianness.
        if line.type == 'regex':
            # Regex types are already compiled expressions.
            # Note that since re.finditer is used, unless the specified
            # regex accounts for it, overlapping signatures will be ignored.
            return line.value
        if line.type == 'string':
            restr = line.value
        elif line.size == 1:
            restr = chr(line.value)
        elif line.size == 2:
            if line.endianness == '<':
                restr = chr(line.value & 0xFF) + chr(line.value >> 8)
            elif line.endianness == '>':
                restr = chr(line.value >> 8) + chr(line.value & 0xFF)
        elif line.size == 4:
            if line.endianness == '<':
                restr = (chr(line.value & 0xFF) +
                         chr((line.value >> 8) & 0xFF) +
                         chr((line.value >> 16) & 0xFF) +
                         chr(line.value >> 24))
            elif line.endianness == '>':
                restr = (chr(line.value >> 24) +
                         chr((line.value >> 16) & 0xFF) +
                         chr((line.value >> 8) & 0xFF) +
                         chr(line.value & 0xFF))
        elif line.size == 8:
            if line.endianness == '<':
                restr = (chr(line.value & 0xFF) +
                         chr((line.value >> 8) & 0xFF) +
                         chr((line.value >> 16) & 0xFF) +
                         chr((line.value >> 24) & 0xFF) +
                         chr((line.value >> 32) & 0xFF) +
                         chr((line.value >> 40) & 0xFF) +
                         chr((line.value >> 48) & 0xFF) +
                         chr(line.value >> 56))
            elif line.endianness == '>':
                restr = (chr(line.value >> 56) +
                         chr((line.value >> 48) & 0xFF) +
                         chr((line.value >> 40) & 0xFF) +
                         chr((line.value >> 32) & 0xFF) +
                         chr((line.value >> 24) & 0xFF) +
                         chr((line.value >> 16) & 0xFF) +
                         chr((line.value >> 8) & 0xFF) +
                         chr(line.value & 0xFF))

        # Since re.finditer is used on a per-signature basis, signatures should be crafted carefully
        # to ensure that they aren't potentially self-overlapping (e.g., a signature of "ABCDAB" could
        # be confused by the byte sequence "ABCDABCDAB"). The longer the signature, the less likely an
        # unintentional overlap is, although files could still be maliciously crafted to cause false
        # negative results.
        #
        # Thus, unless a signature has been explicitly marked as knowingly overlapping ('{overlap}'),
        # spit out a warning about any self-overlapping signatures.
        if not binwalk.core.compat.has_key(line.tags, 'overlap'):
            for i in range(1, line.size):
                if restr[i:] == restr[0:(line.size - i)]:
                    binwalk.core.common.warning("Signature '%s' is a self-overlapping signature!" % line.text)
                    break

        return re.compile(re.escape(restr))
676747
function _buildRegexFromString(regex) {

        if (!regex || (typeof regex !== "string" && !(regex instanceof RegExp))) {
            _regexDebug();
            return false;
        }

        if (typeof regex !== 'string') {
            regex = regex.toString();
        }

        var separator = regex.charAt(0),
            index = regex.length - 1,
            pattern,
            modifier,
            rule;

        while (index > 0) {
            if (/[gimsxeU]/.test(regex.charAt(index))) {
                index--;
            } else {
                break;
            }
        }

        if (regex.charAt(index) !== separator) {
            separator = null;
        }

        if (separator && index !== regex.length - 1) {
            modifier = regex.substr(index + 1, regex.length - 1);
        }

        if (separator) {
            pattern = regex.substr(1, index - 1);
        } else {
            pattern = regex;
        }

        try {
            rule = new RegExp(pattern, modifier);
        } catch (error) {
            _regexDebug();
            return false;
        }

        return rule;

        function _regexDebug() {
            // {debug}
            window.Debug.log({
                'function': '_buildRegexFromString()',
                'arguments': '{pattern: {' + (pattern || '') + '}, modifier: {' + (modifier || '') + '}',
                'message': 'WARNING - Invalid regex given: ' + regex
            });
            window.Debug.print();
            // {/debug}
        }

    }
111810
def compile_search(pattern, flags=0, **kwargs):
    """"""

    return _regex.compile(_apply_search_backrefs(pattern, flags), flags, **kwargs)
533617
def process_regex(self, key):
        
        return re.compile(self.output_dict[key]) if \
            key in self.output_dict else None
928805
def setup_regex(self):
        """"""
        self._RX_CONTAINS = r"^\s*contains[^\n]*?$"
        self.RE_CONTAINS = re.compile(self._RX_CONTAINS, re.M | re.I)

        #Setup a regex that can extract information about both functions and subroutines
        self._RX_EXEC = r"\n[ \t]*((?P<type>character|real|type|logical|integer|complex)?" + \
                        r"(?P<kind>\([a-z0-9_]+\))?)?((?P<modifiers>[\w, \t]+?))?[ \t]*" + \
                        r"(?P<codetype>subroutine|function)\s+(?P<name>[^(]+)" + \
                        r"\s*\((?P<parameters>[^)]*)\)(?P<result>\sresult\([a-z0-9_]+\))?" + \
                        r"(?P<contents>.+?)end\s*(?P=codetype)\s+(?P=name)"
        self.RE_EXEC = re.compile(self._RX_EXEC, re.DOTALL | re.I)
        #Regex for the signature is almost identical to the full executable, but it doesn't
        #look for any contents after the parameter list.
        self._RX_SIG =  r"((?P<type>character|real|type|logical|integer|complex)?" + \
                        r"(?P<kind>\([a-z0-9_]+\))?)?(,?(?P<modifiers>[^\n]+?))?\s*" + \
                        r"(?P<codetype>subroutine|function)\s+(?P<name>[^(]+)" + \
                        r"\s*\((?P<parameters>[^)]*)\)"
        self.RE_SIG = re.compile(self._RX_SIG, re.I)

        #The contents of the executable already have any & line continuations
        #removed, so we can use a simple multiline regex.
        self._RX_ASSIGN = r"^(?P<assignee>[^!<=\n/]+?)=[^\n]+?$"
        self.RE_ASSIGN = re.compile(self._RX_ASSIGN, re.M)

        self._RX_DEPEND = r"^\s*(?P<sub>call\s+)?(?P<exec>[a-z0-9_%]+\s*\([^\n]+)$"
        self.RE_DEPEND = re.compile(self._RX_DEPEND, re.M | re. I)

        self._RX_DEPCLEAN = r"(?P<key>[a-z0-9_%]+)\("
        self.RE_DEPCLEAN = re.compile(self._RX_DEPCLEAN, re.I)

        self._RX_CONST = '[^"\']+(?P<const>["\'][^\'"]+["\'])'
        self.RE_CONST = re.compile(self._RX_CONST)

        self._RX_COMMENTS = r'\s*![^\n"]+?\n'
        self.RE_COMMENTS = re.compile(self._RX_COMMENTS)
654614
def regexpCompile(regexp):
    
    ret = libxml2mod.xmlRegexpCompile(regexp)
    if ret is None:raise treeError('xmlRegexpCompile() failed')
    return xmlReg(_obj=ret)
142634
def compile_excludes(self):
        """"""
        self.compiled_exclude_files = []
        for pattern in self.exclude_files:
            try:
                self.compiled_exclude_files.append(re.compile(pattern))
            except re.error as e:
                raise ValueError(
                    "Bad python regex in exclude '%s': %s" % (pattern, str(e)))
573127
def generate(regex, Ns):
    ""
    return sorted(regex_parse(regex)[0](Ns),
                  key=lambda s: (len(s), s))
383867
def _compile_tag_re(self):
        
        queue_tag_list = []
        for regex_str, tags in iteritems(self._queue_tag_re):
            try:
                queue_tag_list.append([re.compile(regex_str), [t.strip() for t in tags.split(',')]])
            except TypeError:
                log.warning('{} is not a valid regular expression and will be ignored'.format(regex_str))
        return queue_tag_list
1325790
def _make_regex(self):
        
        rxp = "|".join(
            map(self._address_rxp, self.keys()),
        )
        self._regex = re.compile(
            rxp,
            re.IGNORECASE,
        )
1016509
def _compile(self, p):
        
        if self._is_value_filter(p) and p[0] == '=~':
            try:
                p[2] = re.compile(p[2])
            except:  # Python doesn't document exactly what exceptions re.compile throws
                raise ValueError('Bad regex - {0}'.format(p[2]))
        elif self._is_operator(p):
            for operator_or_filter in (p[1] if p[0] != '!' else [p[1]]):
                self._compile(operator_or_filter)
215020
def _compile(self, expression):
        

        x = self.RE_PYTHON_VAR.sub('(?:\\1,)', expression)
        x = self.RE_SPACES.sub('', x)
        return re.compile(x)
286105
def regex(self, *pattern, **kwargs):
        
        self.pattern(self.build_re(*pattern, **kwargs))
        return self
926321
def _process_regex(cls, regex, rflags, state):
        """"""
        if isinstance(regex, Future):
            regex = regex.get()
        return re.compile(regex, rflags).match
1108805
def _encode_regex(name, value, dummy0, dummy1):
    """"""
    flags = value.flags
    # Python 2 common case
    if flags == 0:
        return b"\x0B" + name + _make_c_string_check(value.pattern) + b"\x00"
    # Python 3 common case
    elif flags == re.UNICODE:
        return b"\x0B" + name + _make_c_string_check(value.pattern) + b"u\x00"
    else:
        sflags = b""
        if flags & re.IGNORECASE:
            sflags += b"i"
        if flags & re.LOCALE:
            sflags += b"l"
        if flags & re.MULTILINE:
            sflags += b"m"
        if flags & re.DOTALL:
            sflags += b"s"
        if flags & re.UNICODE:
            sflags += b"u"
        if flags & re.VERBOSE:
            sflags += b"x"
        sflags += b"\x00"
        return b"\x0B" + name + _make_c_string_check(value.pattern) + sflags