Python re._pattern_type() Examples
The following are 30
code examples of re._pattern_type().
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 also want to check out all available functions/classes of the module
re
, or try the search function
.
Example #1
Source File: pool.py From python-f5 with Apache License 2.0 | 6 votes |
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 #2
Source File: inference.py From elasticintel with GNU General Public License v3.0 | 6 votes |
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 #3
Source File: inference.py From Splunking-Crime with GNU Affero General Public License v3.0 | 6 votes |
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 #4
Source File: android_layout.py From ATX with Apache License 2.0 | 6 votes |
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 #5
Source File: select.py From nerodia with MIT License | 6 votes |
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 #6
Source File: db_interface.py From tfutils with MIT License | 6 votes |
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 #7
Source File: utils.py From faces with GNU General Public License v2.0 | 6 votes |
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 #8
Source File: selector_builder.py From nerodia with MIT License | 6 votes |
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 #9
Source File: node.py From python-f5 with Apache License 2.0 | 6 votes |
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 #10
Source File: wait.py From nerodia with MIT License | 6 votes |
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 #11
Source File: __init__.py From python-aptly with GNU General Public License v2.0 | 6 votes |
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 #12
Source File: fetching.py From beavy with Mozilla Public License 2.0 | 6 votes |
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 #13
Source File: adjacent.py From nerodia with MIT License | 6 votes |
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
Source File: linting.py From bellybutton with MIT License | 5 votes |
def lint_file(filepath, file_contents, rules): """Run rules against file, yielding any failures.""" matching_rules = [ rule for rule in rules if rule_settings_match(rule, filepath) ] if not matching_rules: return ignored_lines = get_ignored_lines(file_contents) xml_ast = file_contents_to_xml_ast(file_contents) # todo - use caching module? for rule in sorted(matching_rules, key=attrgetter('name')): # TODO - hacky - need to find better way to do this (while keeping chain) # TODO - possibly having both filepath and contents/input supplied? if isinstance(rule.expr, XPath): matching_lines = set(find_in_ast( xml_ast, rule.expr.path, return_lines=True )) elif isinstance(rule.expr, re._pattern_type): matching_lines = { file_contents[:match.start()].count('\n') + 1 # TODO - slow for match in re.finditer(rule.expr, file_contents) } elif callable(rule.expr): matching_lines = set(rule.expr(file_contents)) else: continue # todo - maybe throw here? if rule.settings.allow_ignore: matching_lines -= ignored_lines if not matching_lines: yield LintingResult(rule, filepath, succeeded=True, lineno=None) for line in matching_lines: yield LintingResult(rule, filepath, succeeded=False, lineno=line)
Example #15
Source File: test_re.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #16
Source File: __init__.py From pheweb with GNU Affero General Public License v3.0 | 5 votes |
def extract_phenocode_from_filepath(phenolist, regex): print("NOTE: working with {} phenos".format(len(phenolist))) re_pattern_type = re._pattern_type if hasattr(re, '_pattern_type') else re.Pattern # changed in py3.7 if not isinstance(regex, re_pattern_type): regex = re.compile(regex) for pheno in phenolist: if 'assoc_files' not in pheno: raise PheWebError("ERROR: At least one phenotype doesn't have the key 'assoc_files'.") if not pheno['assoc_files']: raise PheWebError("ERROR: At least one phenotype has an empty 'assoc_files' list.") phenocodes = [] for assoc_filepath in pheno['assoc_files']: match = re.search(regex, assoc_filepath) if match is None: raise PheWebError("ERROR: The regex {!r} doesn't match the filepath {!r}".format(regex.pattern, assoc_filepath)) groups = match.groups() if len(groups) != 1: raise PheWebError("ERROR: The regex {!r} doesn't capture any groups on the filepath {!r}! You're using parentheses without backslashes, right?".format(regex.pattern, assoc_filepath)) phenocodes.append(groups[0]) if len(set(phenocodes)) != 1: raise PheWebError("ERROR: At least one phenotype gets multiple different phenocodes from its several association filepaths. Here they are: {!r}".format(list(set(phenocodes)))) if 'phenocode' in pheno: if pheno['phenocode'] != phenocodes[0]: raise PheWebError("""\ ERROR: The regex {!r} matched the filepaths {!r} to produce the phenocode {!r}. But that phenotype already had a phenocode, {!r}. """.format(regex.pattern, pheno['assoc_files'], phenocodes[0], pheno['phenocode'])) pheno['phenocode'] = phenocodes[0] return phenolist
Example #17
Source File: test_re.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
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 #18
Source File: JSONEncoder.py From coala with GNU Affero General Public License v3.0 | 5 votes |
def create_json_encoder(**kwargs): class JSONEncoder(json.JSONEncoder): @classmethod def _filter_params(cls, op, nop): params = set(op) | set(nop) return {key: kwargs[key] for key in set(kwargs) & (params)} def default(self, obj): if hasattr(obj, '__json__'): fdata = FunctionMetadata.from_function(obj.__json__) params = self._filter_params( fdata.optional_params, fdata.non_optional_params) return obj.__json__(**params) elif isinstance(obj, collections.Iterable): return list(obj) elif isinstance(obj, datetime): return obj.isoformat() elif hasattr(obj, '__getitem__') and hasattr(obj, 'keys'): return dict(obj) elif hasattr(obj, '__dict__'): return {member: getattr(obj, member) for member in get_public_members(obj)} elif isinstance(obj, re._pattern_type): return obj.pattern return json.JSONEncoder.default(self, obj) return JSONEncoder
Example #19
Source File: responses.py From jarvis with GNU General Public License v2.0 | 5 votes |
def _url_matches(self, url, other, match_querystring=False): if _is_string(url): if match_querystring: return self._url_matches_strict(url, other) else: url_without_qs = url.split('?', 1)[0] other_without_qs = other.split('?', 1)[0] return url_without_qs == other_without_qs elif isinstance(url, re._pattern_type) and url.match(other): return True else: return False
Example #20
Source File: series.py From modin with Apache License 2.0 | 5 votes |
def count(self, pat, flags=0, **kwargs): if not isinstance(pat, (str, _pattern_type)): raise TypeError("first argument must be string or compiled pattern") return Series( query_compiler=self._query_compiler.str_count(pat, flags=flags, **kwargs) )
Example #21
Source File: series.py From modin with Apache License 2.0 | 5 votes |
def findall(self, pat, flags=0, **kwargs): if not isinstance(pat, (str, _pattern_type)): raise TypeError("first argument must be string or compiled pattern") return Series( query_compiler=self._query_compiler.str_findall(pat, flags=flags, **kwargs) )
Example #22
Source File: series.py From modin with Apache License 2.0 | 5 votes |
def match(self, pat, case=True, flags=0, na=np.NaN): if not isinstance(pat, (str, _pattern_type)): raise TypeError("first argument must be string or compiled pattern") return Series( query_compiler=self._query_compiler.str_match(pat, flags=flags, na=na) )
Example #23
Source File: test_re.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
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 #24
Source File: rule.py From python-f5 with Apache License 2.0 | 5 votes |
def _get(cls, lb, pattern=None, minimal=False): names = cls._get_list(lb) if not names: return [] if pattern is not None: if not isinstance(pattern, re._pattern_type): pattern = re.compile(pattern) names = [rule_name for rule_name in names if pattern.match(rule_name)] return cls._get_objects(lb, names, minimal)
Example #25
Source File: arch.py From archinfo with BSD 2-Clause "Simplified" License | 5 votes |
def register_arch(regexes, bits, endness, my_arch): """ Register a new architecture. Architectures are loaded by their string name using ``arch_from_id()``, and this defines the mapping it uses to figure it out. Takes a list of regular expressions, and an Arch class as input. :param regexes: List of regular expressions (str or SRE_Pattern) :type regexes: list :param bits: The canonical "bits" of this architecture, ex. 32 or 64 :type bits: int :param endness: The "endness" of this architecture. Use Endness.LE, Endness.BE, Endness.ME, "any", or None if the architecture has no intrinsic endianness. :type endness: str or None :param class my_arch: :return: None """ if not isinstance(regexes, list): raise TypeError("regexes must be a list") for rx in regexes: if not isinstance(rx, str) and not isinstance(rx,re._pattern_type): raise TypeError("Each regex must be a string or compiled regular expression") try: re.compile(rx) except: raise ValueError('Invalid Regular Expression %s' % rx) #if not isinstance(my_arch,Arch): # raise TypeError("Arch must be a subclass of archinfo.Arch") if not isinstance(bits, int): raise TypeError("Bits must be an int") if endness is not None: if endness not in (Endness.BE, Endness.LE, Endness.ME, 'any'): raise TypeError("Endness must be Endness.BE, Endness.LE, or 'any'") arch_id_map.append((regexes, bits, endness, my_arch)) if endness == 'any': all_arches.append(my_arch(Endness.BE)) all_arches.append(my_arch(Endness.LE)) else: all_arches.append(my_arch(endness))
Example #26
Source File: element_locator_tests.py From nerodia with MIT License | 5 votes |
def test_raises_correct_exception_if_selector_value_is_not_a_list_string_unicode_regexp_or_boolean(self, browser, expect_all): message = 'expected one of [{}, {}, {}, {}], got ' \ '123:{}'.format(Pattern, bool, six.text_type, six.binary_type, int) with pytest.raises(TypeError) as e: locate_one(browser, {'foo': 123}) assert e.value.args[0] == message
Example #27
Source File: select.py From nerodia with MIT License | 5 votes |
def _find_options(self, how, term): types = [six.text_type, six.binary_type, int, Pattern] found = [] def func(sel): if type(term) in types: collection = sel.options(value=term) if how == 'value' else [] if not list(collection): collection = sel.options(text=term) if not list(collection): collection = sel.options(label=term) if collection: found.append(collection) return False else: return not found and nerodia.relaxed_locate else: raise TypeError('expected {!r}, got {}:{}'.format(types, term, term.__class__)) try: Wait.until_not(func, object=self) if found: return found[0] self._raise_no_value_found(term) except TimeoutError: self._raise_no_value_found(term)
Example #28
Source File: matcher.py From nerodia with MIT License | 5 votes |
def _matches_values(self, found, expected): if isinstance(expected, Pattern): return re.search(expected, found) is not None else: return expected == found
Example #29
Source File: selector_builder.py From nerodia with MIT License | 5 votes |
def _process_attribute(self, key, value): if isinstance(value, Pattern): return self._predicate_conversion(key, value) else: return self._predicate_expression(key, value)
Example #30
Source File: selector_builder.py From nerodia with MIT License | 5 votes |
def _text_string(self): if self.adjacent is not None: return super(XPath, self)._text_string # text locator is already dealt with in #tag_name_string value = self.selector.pop('value', None) if value is None: return '' elif isinstance(value, Pattern): res = '[{} or {}]'.format(self._predicate_conversion('text', value), self._predicate_conversion('value', value)) self.built.pop('text', None) return res else: return '[{} or {}]'.format(self._predicate_expression('text', value), self._predicate_expression('value', value))