Python re._pattern_type() Examples

The following are 30 code examples for showing how to use re._pattern_type(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module re , or try the search function .

Example 1
Project: beavy   Author: beavyHQ   File: fetching.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def _matches(data, **kwargs):
    for key, match in kwargs.items():
        try:
            given_value = data[key]
        except KeyError:
            return False
        else:
            if isinstance(match, re._pattern_type):
                if not match.match(given_value):
                    return False
            elif callable(match):
                if not match(given_value):
                    return False
            else:
                if match != given_value:
                    return False
    return True 
Example 2
Project: python-aptly   Author: tcpcloud   File: __init__.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _publish_match(self, publish, names=False, name_only=False):
        """
        Check if publish name matches list of names or regex patterns
        """
        if names:
            for name in names:
                if not name_only and isinstance(name, re._pattern_type):
                    if re.match(name, publish.name):
                        return True
                else:
                    operand = name if name_only else [name, './%s' % name]
                    if publish in operand:
                        return True
            return False
        else:
            return True 
Example 3
Project: faces   Author: skarlekar   File: utils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def preprocess_string(self, html_string):
        """Here we can modify the text, before it's parsed."""
        if not html_string:
            return html_string
        # Remove silly  » and – chars.
        html_string = html_string.replace(u' \xbb', u'')
        html_string = html_string.replace(u'–', u'-')
        try:
            preprocessors = self.preprocessors
        except AttributeError:
            return html_string
        for src, sub in preprocessors:
            # re._pattern_type is present only since Python 2.5.
            if callable(getattr(src, 'sub', None)):
                html_string = src.sub(sub, html_string)
            elif isinstance(src, str):
                html_string = html_string.replace(src, sub)
            elif callable(src):
                try:
                    html_string = src(html_string)
                except Exception, e:
                    _msg = '%s: caught exception preprocessing html'
                    self._logger.error(_msg, self._cname, exc_info=True)
                    continue
        ##print html_string.encode('utf8') 
Example 4
Project: tfutils   Author: neuroailab   File: db_interface.py    License: MIT License 6 votes vote down vote up
def filter_var_list(self, var_list):
        """Filter checkpoint vars for those to be restored.

        Args:
            checkpoint_vars (list): Vars that can be restored from checkpoint.
            to_restore (list[str] or regex, optional): Selects vars to restore.

        Returns:
            list: Variables to be restored from checkpoint.

        """
        if not self.to_restore:
            return var_list
        elif isinstance(self.to_restore, re._pattern_type):
            return {name: var for name, var in var_list.items()
                    if self.to_restore.match(name)}
        elif isinstance(self.to_restore, list):
            return {name: var for name, var in var_list.items()
                    if name in self.to_restore}
        raise TypeError('to_restore ({}) unsupported.'.format(type(self.to_restore))) 
Example 5
Project: python-f5   Author: tdevelioglu   File: pool.py    License: Apache License 2.0 6 votes vote down vote up
def _get(cls, lb, pattern=None, minimal=False):
        names = cls._lbcall(lb, 'get_list')

        if not names:
            return []

        if pattern is not None:
            if not isinstance(pattern, re._pattern_type):
                pattern = re.compile(pattern)
            names = [name for name in names if pattern.match(name)]

        return cls._get_objects(lb, names, minimal)

    ###########################################################################
    # Public API
    ########################################################################### 
Example 6
Project: python-f5   Author: tdevelioglu   File: node.py    License: Apache License 2.0 6 votes vote down vote up
def _get(cls, lb, pattern=None, minimal=False):
        names = cls._lbcall(lb, 'get_list')

        if not names:
            return []

        if pattern is not None:
            if not isinstance(pattern, re._pattern_type):
                pattern = re.compile(pattern)
            names = [name for name in names if pattern.match(name)]

        return cls._get_objects(lb, names, minimal)

    ###########################################################################
    # Public API
    ########################################################################### 
Example 7
Project: ATX   Author: NetEaseGame   File: android_layout.py    License: Apache License 2.0 6 votes vote down vote up
def _filter_nodes(self, cond, nodes=None):
        if nodes is None:
            nodes = self.nodes
        res = []
        for n in nodes:
            match = True
            for k, v in cond.iteritems():
                attr = getattr(n, k)
                if isinstance(v, re._pattern_type) and \
                    isinstance(attr, basestring) and v.match(attr) is None:
                    match = False
                    break
                elif attr != v:
                    match = False
                    break
            if match:
                res.append(n)
        return res 
Example 8
Project: Splunking-Crime   Author: nccgroup   File: inference.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def is_re(obj):
    """
    Check if the object is a regex pattern instance.

    Parameters
    ----------
    obj : The object to check.

    Returns
    -------
    is_regex : bool
        Whether `obj` is a regex pattern.

    Examples
    --------
    >>> is_re(re.compile(".*"))
    True
    >>> is_re("foo")
    False
    """

    return isinstance(obj, re._pattern_type) 
Example 9
Project: elasticintel   Author: securityclippy   File: inference.py    License: GNU General Public License v3.0 6 votes vote down vote up
def is_re(obj):
    """
    Check if the object is a regex pattern instance.

    Parameters
    ----------
    obj : The object to check.

    Returns
    -------
    is_regex : bool
        Whether `obj` is a regex pattern.

    Examples
    --------
    >>> is_re(re.compile(".*"))
    True
    >>> is_re("foo")
    False
    """

    return isinstance(obj, re._pattern_type) 
Example 10
Project: nerodia   Author: watir   File: select.py    License: MIT License 6 votes vote down vote up
def _js_select_by(self, term, number):
        if isinstance(term, Pattern):
            js_rx = term.pattern
            js_rx = js_rx.replace('\\A', '^', 1)
            js_rx = js_rx.replace('\\Z', '$', 1)
            js_rx = js_rx.replace('\\z', '$', 1)
            js_rx = re.sub(r'\(\?#.+\)', '', js_rx)
            js_rx = re.sub(r'\(\?-\w+:', '(', js_rx)
        elif type(term) in [six.text_type, six.binary_type]:
            js_rx = '^{}$'.format(term)
        else:
            raise TypeError('expected String or Regexp, got {}'.format(term))

        for way in ['text', 'label', 'value']:
            self._element_call(lambda: self._execute_js('selectOptions{}'.format(way.capitalize()),
                                                        self, js_rx, str(number)))
            if self._is_matching_option(way, term):
                return self.selected_options[0].text

        self._raise_no_value_found(term) 
Example 11
Project: nerodia   Author: watir   File: selector_builder.py    License: MIT License 6 votes vote down vote up
def _label_element_string(self):
        label = self.selector.pop('label_element', None)
        if label is None:
            return ''

        key = 'contains_text' if isinstance(label, Pattern) else 'text'

        value = self._process_attribute(key, label)

        if 'contains_text' in self.built:
            self.built['label_element'] = self.built.pop('contains_text')

        # TODO: This conditional can be removed when we remove this deprecation
        if isinstance(label, Pattern):
            self.built['label_element'] = label
            return ''
        else:
            return "[@id=//label[{0}]/@for or parent::label[{0}]]".format(value) 
Example 12
Project: nerodia   Author: watir   File: wait.py    License: MIT License 6 votes vote down vote up
def _match_attributes(self, obj, until=True):
        from ..elements.element import Element

        def check(key):
            expected = obj.get(key)
            if isinstance(self, Element) and not hasattr(self, key):
                actual = self.get_attribute(key)
            else:
                attr = getattr(self, key)
                actual = attr() if callable(attr) else attr
            if isinstance(expected, Pattern):
                return re.search(expected, actual) is not None
            else:
                return expected == actual

        def func(*args):
            truthy = all if until else any
            return truthy(check(key) for key in obj)
        return func 
Example 13
Project: nerodia   Author: watir   File: adjacent.py    License: MIT License 6 votes vote down vote up
def _xpath_adjacent(self, **kwargs):
        from .elements.html_elements import HTMLElement, HTMLElementCollection
        import nerodia

        plural = kwargs.pop('plural', None)
        index = kwargs.pop('index', None)
        tag_name = kwargs.get('tag_name')

        if not (plural or any(isinstance(val, Pattern) for val in kwargs.values())):
            kwargs['index'] = index or 0

        if not plural and tag_name:
            klass = nerodia.element_class_for(tag_name)
        elif not plural:
            klass = HTMLElement
        elif tag_name:
            klass = nerodia.element_class_for('{}_collection'.format(tag_name),
                                              HTMLElementCollection)
        else:
            klass = HTMLElementCollection

        return klass(self, kwargs) 
Example 14
Project: jawfish   Author: war-and-code   File: test_re.py    License: MIT License 5 votes vote down vote up
def test_compile(self):
        # Test return value when given string and pattern as parameter
        pattern = re.compile('random pattern')
        self.assertIsInstance(pattern, re._pattern_type)
        same_pattern = re.compile(pattern)
        self.assertIsInstance(same_pattern, re._pattern_type)
        self.assertIs(same_pattern, pattern)
        # Test behaviour when not given a string or pattern as parameter
        self.assertRaises(TypeError, re.compile, 0) 
Example 15
Project: recordlinkage   Author: J535D165   File: types.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_re(obj):
    return isinstance(obj, re._pattern_type) 
Example 16
Project: recipes-py   Author: luci   File: magic_check_fn.py    License: Apache License 2.0 5 votes vote down vote up
def render_user_value(val):
  """Takes a subexpression user value, and attempts to render it in the most
  useful way possible.

  Currently this will use render_re for compiled regular expressions, and will
  fall back to repr() for everything else.

  It should be the goal of this function to return an `eval`able string that
  would yield the equivalent value in a python interpreter.
  """
  if isinstance(val, re._pattern_type):
    return render_re(val)
  return repr(val) 
Example 17
Project: PrivacyScore   Author: PrivacyScore   File: serverleak.py    License: GNU General Public License v3.0 5 votes vote down vote up
def process_test_data(raw_data: list, previous_results: dict) -> Dict[str, Dict[str, object]]:
    leaks = []
    result = {}
    
    url = None
    if 'url' in raw_data:
        url = raw_data['url']['data'].decode()

    for trial, pattern in TRIALS:
        if url:
            if callable(trial):
                trial = trial(url)
                if trial is None:
                    continue
        if trial not in raw_data:
            # Test raw data too old or particular request failed.
            continue
        response = json.loads(raw_data[trial]['data'].decode())
        if response['status_code'] == 200:
            # The pattern can have three different types.
            # - If it is a simple string, we only check if it is contained in the response
            if isinstance(pattern, str):
                if pattern in response['text']:
                    leaks.append(trial)
            # - If it is a RegEx object, we perform a pattern match
            elif isinstance(pattern, re._pattern_type):
                if re.match(response['text']):
                    leaks.append(trial)
            # - If it is callable, we call it with the response text and check the return value
            elif callable(pattern):
                if pattern(response['text']):
                    leaks.append(trial)

    result['leaks'] = leaks
    return result 
Example 18
Project: paramz   Author: sods   File: parameterized.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def grep_param_names(self, regexp):
        """
        create a list of parameters, matching regular expression regexp
        """
        if not isinstance(regexp, _pattern_type): regexp = compile(regexp)
        found_params = []
        def visit(innerself, regexp):
            if (innerself is not self) and regexp.match(innerself.hierarchy_name().partition('.')[2]):
                found_params.append(innerself)
        self.traverse(visit, regexp)
        return found_params 
Example 19
Project: ironpython2   Author: IronLanguages   File: test_re.py    License: Apache License 2.0 5 votes vote down vote up
def test_compile(self):
        # Test return value when given string and pattern as parameter
        pattern = re.compile('random pattern')
        self.assertIsInstance(pattern, re._pattern_type)
        same_pattern = re.compile(pattern)
        self.assertIsInstance(same_pattern, re._pattern_type)
        self.assertIs(same_pattern, pattern)
        # Test behaviour when not given a string or pattern as parameter
        self.assertRaises(TypeError, re.compile, 0) 
Example 20
Project: FIR   Author: certsocietegenerale   File: links.py    License: GNU General Public License v3.0 5 votes vote down vote up
def register_reverse_link(self, parser_regex, url_name, model=None, reverse=None):
        """
        Registers a new parser for links using Django urlconf
        :param parser_regex: string or regex object
        :param url_name: urlconf name
        :param model: model label (app_label.model_name) or model class (used by fir_relations)
        :param reverse: string template to render object id to text (used by fir_relations)
        """
        if not isinstance(parser_regex, re._pattern_type):
            parser_regex = re.compile(parser_regex)
        self.reverse_links.append((parser_regex, url_name))
        if model is not None:
            if not isinstance(model, six.string_types) and issubclass(models.Model, model):
                model = model._meta.label
            self.model_links[model] = (parser_regex, url_name, reverse) 
Example 21
Project: FIR   Author: certsocietegenerale   File: links.py    License: GNU General Public License v3.0 5 votes vote down vote up
def register_regex_link(self, parser_regex, template):
        """
        Registers a new parser for links using regex replacement
        :param parser_regex: string or regex object
        :param template: template to pass to regex expand
        """
        if not isinstance(parser_regex, re._pattern_type):
            parser_regex = re.compile(parser_regex)
        self.regex_links.append((parser_regex, template)) 
Example 22
Project: BinderFilter   Author: dxwu   File: test_re.py    License: MIT License 5 votes vote down vote up
def test_compile(self):
        # Test return value when given string and pattern as parameter
        pattern = re.compile('random pattern')
        self.assertIsInstance(pattern, re._pattern_type)
        same_pattern = re.compile(pattern)
        self.assertIsInstance(same_pattern, re._pattern_type)
        self.assertIs(same_pattern, pattern)
        # Test behaviour when not given a string or pattern as parameter
        self.assertRaises(TypeError, re.compile, 0) 
Example 23
Project: Computable   Author: ktraunmueller   File: common.py    License: MIT License 5 votes vote down vote up
def is_re(obj):
    return isinstance(obj, re._pattern_type) 
Example 24
Project: oss-ftp   Author: aliyun   File: test_re.py    License: MIT License 5 votes vote down vote up
def test_compile(self):
        # Test return value when given string and pattern as parameter
        pattern = re.compile('random pattern')
        self.assertIsInstance(pattern, re._pattern_type)
        same_pattern = re.compile(pattern)
        self.assertIsInstance(same_pattern, re._pattern_type)
        self.assertIs(same_pattern, pattern)
        # Test behaviour when not given a string or pattern as parameter
        self.assertRaises(TypeError, re.compile, 0) 
Example 25
Project: ReGraph   Author: Kappa-Dev   File: attribute_sets.py    License: MIT License 5 votes vote down vote up
def _regex_to_string(a):
    if isinstance(a, str):
        return a
    elif isinstance(a, re._pattern_type):
        return a.pattern
    elif isinstance(a, RegexSet):
        if a.pattern is not None:
            return a.pattern
        else:
            return None
    else:
        raise AttributeSetError("Cannot convert regex to string!") 
Example 26
Project: Fluid-Designer   Author: Microvellum   File: test_re.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_compile(self):
        # Test return value when given string and pattern as parameter
        pattern = re.compile('random pattern')
        self.assertIsInstance(pattern, re._pattern_type)
        same_pattern = re.compile(pattern)
        self.assertIsInstance(same_pattern, re._pattern_type)
        self.assertIs(same_pattern, pattern)
        # Test behaviour when not given a string or pattern as parameter
        self.assertRaises(TypeError, re.compile, 0) 
Example 27
Project: robobrowser   Author: jmcarp   File: helpers.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def match_text(text, tag):
    if isinstance(text, string_types):
        return text in tag.text
    if isinstance(text, re._pattern_type):
        return text.search(tag.text) 
Example 28
Project: ironpython3   Author: IronLanguages   File: test_re.py    License: Apache License 2.0 5 votes vote down vote up
def test_compile(self):
        # Test return value when given string and pattern as parameter
        pattern = re.compile('random pattern')
        self.assertIsInstance(pattern, re._pattern_type)
        same_pattern = re.compile(pattern)
        self.assertIsInstance(same_pattern, re._pattern_type)
        self.assertIs(same_pattern, pattern)
        # Test behaviour when not given a string or pattern as parameter
        self.assertRaises(TypeError, re.compile, 0) 
Example 29
Project: aresponses   Author: CircleUp   File: utils.py    License: MIT License 5 votes vote down vote up
def _text_matches_pattern(pattern, text):
    # This is needed for compatibility with old Python versions
    try:
        pattern_class = re.Pattern
    except AttributeError:
        pattern_class = re._pattern_type
    if isinstance(pattern, str):
        if pattern == text:
            return True
    elif isinstance(pattern, pattern_class):
        if pattern.search(text):
            return True
    return False 
Example 30
Project: python-f5   Author: tdevelioglu   File: poolmember.py    License: Apache License 2.0 5 votes vote down vote up
def _get(cls, lb, pools=None, pattern=None, minimal=False):
        if pools is not None:
            if isinstance(pools, list):
                pools = [pool.name for pool in pools]
            else:
                if isinstance(pools, str):
                    pools = [pools]
                else:
                    pools = [pools.name]
        else:
            pools = f5.Pool._get(lb)

        # no pools no glory
        if not pools:
            return []

        addrportsq2 = cls._get_list(lb, pools)
        
        if not addrportsq2:
            return []

        if pattern is not None:
            if not isinstance(pattern, re._pattern_type):
                pattern = re.compile(pattern)
            for idx,addrportsq in enumerate(addrportsq2):
                addrportsq2[idx] = [ap for ap in addrportsq if pattern.match('%s:%s' % (ap['address'], ap['port']))]

        return cls._get_objects(lb, pools, addrportsq2, minimal)