based on rule definition, build the regular expression to execute on decode
426415
protected function get_calculated_regexp() {
        $regexp = '/\$@' . $this->linkname;
        foreach ($this->mappings as $key => $value) {
            $regexp .= '\*(\d+)';
        }
        $regexp .= '@\$/';
        return $regexp;
    }
753617
def _interpret_regexp(self, string, flags):
        ''''''
        self.index = 0
        self.length = len(string)
        self.source = string
        self.lineNumber = 0
        self.lineStart = 0
        octal = False
        st = ''
        inside_square = 0
        while (self.index < self.length):
            template = '[%s]' if not inside_square else '%s'
            ch = self.source[self.index]
            self.index += 1
            if ch == '\\':
                ch = self.source[self.index]
                self.index += 1
                if (not isLineTerminator(ch)):
                    if ch == 'u':
                        digs = self.source[self.index:self.index + 4]
                        if len(digs) == 4 and all(isHexDigit(d) for d in digs):
                            st += template % unichr(int(digs, 16))
                            self.index += 4
                        else:
                            st += 'u'
                    elif ch == 'x':
                        digs = self.source[self.index:self.index + 2]
                        if len(digs) == 2 and all(isHexDigit(d) for d in digs):
                            st += template % unichr(int(digs, 16))
                            self.index += 2
                        else:
                            st += 'x'
                    # special meaning - single char.
                    elif ch == '0':
                        st += '\\0'
                    elif ch == 'n':
                        st += '\\n'
                    elif ch == 'r':
                        st += '\\r'
                    elif ch == 't':
                        st += '\\t'
                    elif ch == 'f':
                        st += '\\f'
                    elif ch == 'v':
                        st += '\\v'

                    # unescape special single characters like . so that they are interpreted literally
                    elif ch in REGEXP_SPECIAL_SINGLE:
                        st += '\\' + ch

                    # character groups
                    elif ch == 'b':
                        st += '\\b'
                    elif ch == 'B':
                        st += '\\B'
                    elif ch == 'w':
                        st += '\\w'
                    elif ch == 'W':
                        st += '\\W'
                    elif ch == 'd':
                        st += '\\d'
                    elif ch == 'D':
                        st += '\\D'
                    elif ch == 's':
                        st += template % u' \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff'
                    elif ch == 'S':
                        st += template % u'\u0000-\u0008\u000e-\u001f\u0021-\u009f\u00a1-\u167f\u1681-\u180d\u180f-\u1fff\u200b-\u2027\u202a-\u202e\u2030-\u205e\u2060-\u2fff\u3001-\ufefe\uff00-\uffff'
                    else:
                        if isDecimalDigit(ch):
                            num = ch
                            while self.index < self.length and isDecimalDigit(
                                    self.source[self.index]):
                                num += self.source[self.index]
                                self.index += 1
                            st += '\\' + num

                        else:
                            st += ch  # DONT ESCAPE!!!
                else:
                    self.lineNumber += 1
                    if (ch == '\r' and self.source[self.index] == '\n'):
                        self.index += 1
                    self.lineStart = self.index
            else:
                if ch == '[':
                    inside_square = True
                elif ch == ']':
                    inside_square = False
                st += ch
        # print string, 'was transformed to', st
        return st
818484
function standardizeRule( rule ) {
		rule.elements = convertValidatorToHash( rule.elements, /\s+/ ) || null;
		rule.propertiesOnly = rule.propertiesOnly || ( rule.elements === true );

		var delim = /\s*,\s*/,
			i;

		for ( i in validators ) {
			rule[ i ] = convertValidatorToHash( rule[ i ], delim ) || null;
			rule[ validatorsRequired[ i ] ] = extractRequired( convertValidatorToHash(
				rule[ validatorsRequired[ i ] ], delim ), rule[ i ] ) || null;
		}

		rule.match = rule.match || null;
	}
2896
function applyRules(_string, _ruleSet, _skip) {

      if(_skip.indexOf(_string.toLowerCase()) === -1) {
        var i = 0, rule;
        while(rule = _ruleSet[i++]) {
          if(_string.match(rule[0])) {
            return _string.replace(rule[0], rule[1]);
          }
        }
      }

      return _string;
    }
599352
def rule_to_regex(cls, rule):
        
        if not rule:
            return rule

        # Check if the rule isn't already regexp
        if rule.startswith('/') and rule.endswith('/'):
            if len(rule) > 1:
                rule = rule[1:-1]
            else:
                raise AdblockParsingError('Invalid rule')
            return rule

        # escape special regex characters
        rule = re.sub(r"([.$+?{}()\[\]\\])", r"\\\1", rule)

        # XXX: the resulting regex must use non-capturing groups (?:
        # for performance reasons; also, there is a limit on number
        # of capturing groups, no using them would prevent building
        # a single regex out of several rules.

        # Separator character ^ matches anything but a letter, a digit, or
        # one of the following: _ - . %. The end of the address is also
        # accepted as separator.
        rule = rule.replace("^", "(?:[^\w\d_\-.%]|$)")

        # * symbol
        rule = rule.replace("*", ".*")

        # | in the end means the end of the address
        if rule[-1] == '|':
            rule = rule[:-1] + '$'

        # || in the beginning means beginning of the domain name
        if rule[:2] == '||':
            # XXX: it is better to use urlparse for such things,
            # but urlparse doesn't give us a single regex.
            # Regex is based on http://tools.ietf.org/html/rfc3986#appendix-B
            if len(rule) > 2:
                #          |            | complete part     |
                #          |  scheme    | of the domain     |
                rule = r"^(?:[^:/?#]+:)?(?://(?:[^/?#]*\.)?)?" + rule[2:]

        elif rule[0] == '|':
            # | in the beginning means start of the address
            rule = '^' + rule[1:]

        # other | symbols should be escaped
        # we have "|$" in our regexp - do not touch it
        rule = re.sub("(\|)[^$]", r"\|", rule)

        return rule
513939
def _compile_pattern(self, rule):
        '''  '''
        out = ''
        for i, part in enumerate(self.syntax.split(rule)):
            if i%3 == 0:   out += re.escape(part.replace('\\:',':'))
            elif i%3 == 1: out += '(?P<%s>' % part if part else '(?:'
            else:          out += '%s)' % (part or '[^/]+')
        return re.compile('^%s$'%out)
203883
def decode(self, text: str, prefix: str = "@") -> str:
        """"""

        def callback(match: Match) -> str:
            m = match.groupdict()
            if m["userid"]:
                user = self.users.get(m["userid"], None)
                if user is None:
                    username = m["userid"]
                else:
                    username = user.name
            elif m["alias"]:
                username = m["alias"]
            return f"{prefix}{username}"

        return self.decode_re.sub(callback, text)
128304
def _parse_canonical_regex(doc):
    """"""
    regex = doc['$regularExpression']
    if len(doc) != 1:
        raise TypeError('Bad $regularExpression, extra field(s): %s' % (doc,))
    if len(regex) != 2:
        raise TypeError('Bad $regularExpression must include only "pattern"'
                        'and "options" components: %s' % (doc,))
    return Regex(regex['pattern'], regex['options'])
510755
function amfXDecodeOne(rules, buffer) {
    if (!rules[buffer.readUInt8(0)]) {
        console.log('Unknown field', buffer.readUInt8(0));
        throw new Error("Error: Unknown field");
    }
    return rules[buffer.readUInt8(0)](buffer);
}
820126
function Rule(regexp) {
  this.regexp = regexp;
  var self = this;
  // proxy accumulators methods
  Object.keys(Rule.accumulators).forEach(function(name) {
    self[name] = function() {
      LOG("building rule:", regexp, "->", name);
      self.methodName = name;
      self.accumulatorParams = arguments;
      self.accumulatorBuilder = Rule.accumulators[name];
      return self;
    };
  });
}
1325790
def _make_regex(self):
        
        rxp = "|".join(
            map(self._address_rxp, self.keys()),
        )
        self._regex = re.compile(
            rxp,
            re.IGNORECASE,
        )
1335326
def _construct_regex(cls, fmt):
        """"""
        return re.compile(fmt.format(**vars(cls)), flags=re.U)
1163883
def extend_regex(regexpr):
    
    """
    regex_map = {
        #r'\<': r'\b(?=\w)',
        #r'\>': r'\b(?!\w)',
        r'\<': r'\b' + positive_lookahead(r'\w'),
        r'\>': r'\b' + negative_lookahead(r'\w'),
        ('UNSAFE', r'\x08'): r'\b',
    }
    for key, repl in six.iteritems(regex_map):
        if isinstance(key, tuple):
            search = key[1]
        else:
            search = key
        if regexpr.find(search) != -1:
            if isinstance(key, tuple):
                print('WARNING! Unsafe regex with: %r' % (key,))
            regexpr = regexpr.replace(search, repl)
    return regexpr
285160
def _decoderFromString(cfg):
        
        if isinstance(cfg, (bytes, str)):
            return lambda s: s.decode(cfg, 'replace')
        return cfg
926321
def _process_regex(cls, regex, rflags, state):
        """"""
        if isinstance(regex, Future):
            regex = regex.get()
        return re.compile(regex, rflags).match
637896
def re_filter(text, regexps):
    """"""
    if not regexps:
        return text

    matched_text = []
    compiled_regexps = [re.compile(x) for x in regexps]
    for line in text:
        if line in matched_text:
            continue

        for regexp in compiled_regexps:
            found = regexp.search(line)
            if found and found.group():
                matched_text.append(line)

    return matched_text or text
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