Python re.Pattern() Examples

The following are 30 code examples of re.Pattern(). 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: case.py    From android_universal with MIT License 6 votes vote down vote up
def assertWarnsRegex(self, expected_warning, expected_regex,
                         *args, **kwargs):
        """Asserts that the message in a triggered warning matches a regexp.
        Basic functioning is similar to assertWarns() with the addition
        that only warnings whose messages also match the regular expression
        are considered successful matches.

        Args:
            expected_warning: Warning class expected to be triggered.
            expected_regex: Regex (re.Pattern object or string) expected
                    to be found in error message.
            args: Function to be called and extra positional args.
            kwargs: Extra kwargs.
            msg: Optional message used in case of failure. Can only be used
                    when assertWarnsRegex is used as a context manager.
        """
        context = _AssertWarnsContext(expected_warning, self, expected_regex)
        return context.handle('assertWarnsRegex', args, kwargs) 
Example #2
Source File: wait.py    From nerodia with 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 #3
Source File: post_process.py    From recipes-py with Apache License 2.0 6 votes vote down vote up
def StepCommandRE(check, step_odict, step, expected_patterns):
  """Assert that a step's command matches a given list of regular expressions.

  Args:
    step (str) - The step to check the command of.
    expected_patterns (list(str, re.Pattern)) - Regular expressions to match the
      elements of the step's command. The i-th element of the step's command
      will be matched against the i-th regular expression. If the pattern does
      not match the entire argument string, it is a CHECK failure.

  Usage:
    yield (
        TEST
        + api.post_process(StepCommandRE, 'step-name',
                           ['my', 'command', '.*'])
    )
  """
  cmd = step_odict[step].cmd
  for expected, actual in zip(expected_patterns, cmd):
    check(_fullmatch(expected, actual))
  unmatched = cmd[len(expected_patterns):]
  check('all arguments matched', not unmatched)
  unused = expected_patterns[len(cmd):]
  check('all patterns used', not unused) 
Example #4
Source File: selector_builder.py    From nerodia with 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 #5
Source File: adjacent.py    From nerodia with 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 #6
Source File: permission_relationships.py    From cartography with Apache License 2.0 6 votes vote down vote up
def compile_regex(item):
    r""" Compile a clause into a regex. Clause checking in AWS is case insensitive
    The following regex symbols will be replaced to make AWS * and ? matching a regex
    * -> .* (wildcard)
    ? -> .? (single character wildcard)
    . -> \\. (make period a literal period)

    Arguments:
        item {str} -- the item to create the regex for

    Returns:
        [re.Pattern] -- The precompiled regex pattern.
        If the pattern does not compile it will return an re.Pattern of empty string
    """

    if isinstance(item, str):
        item = item.replace(".", "\\.").replace("*", ".*").replace("?", ".?")
        try:
            item = re.compile(item, flags=re.IGNORECASE)
        except re.error:
            logger.warning(f"Regex did not compile for {item}")
            # in this case it must still return a regex.
            # So it will return an re.Pattern of empry stringm
            item = re.compile("", flags=re.IGNORECASE)
    return item 
Example #7
Source File: select.py    From nerodia with 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 #8
Source File: case.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def assertWarnsRegex(self, expected_warning, expected_regex,
                         *args, **kwargs):
        """Asserts that the message in a triggered warning matches a regexp.
        Basic functioning is similar to assertWarns() with the addition
        that only warnings whose messages also match the regular expression
        are considered successful matches.

        Args:
            expected_warning: Warning class expected to be triggered.
            expected_regex: Regex (re.Pattern object or string) expected
                    to be found in error message.
            args: Function to be called and extra positional args.
            kwargs: Extra kwargs.
            msg: Optional message used in case of failure. Can only be used
                    when assertWarnsRegex is used as a context manager.
        """
        context = _AssertWarnsContext(expected_warning, self, expected_regex)
        return context.handle('assertWarnsRegex', args, kwargs) 
Example #9
Source File: case.py    From Imogen with MIT License 6 votes vote down vote up
def assertWarnsRegex(self, expected_warning, expected_regex,
                         *args, **kwargs):
        """Asserts that the message in a triggered warning matches a regexp.
        Basic functioning is similar to assertWarns() with the addition
        that only warnings whose messages also match the regular expression
        are considered successful matches.

        Args:
            expected_warning: Warning class expected to be triggered.
            expected_regex: Regex (re.Pattern object or string) expected
                    to be found in error message.
            args: Function to be called and extra positional args.
            kwargs: Extra kwargs.
            msg: Optional message used in case of failure. Can only be used
                    when assertWarnsRegex is used as a context manager.
        """
        context = _AssertWarnsContext(expected_warning, self, expected_regex)
        return context.handle('assertWarnsRegex', args, kwargs) 
Example #10
Source File: photoz.py    From gcr-catalogs with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, path, filename_pattern=None):

        if isinstance(filename_pattern, re.Pattern): # pylint: disable=no-member
            filename_re = filename_pattern
        else:
            filename_re = re.compile(filename_pattern)

        basename = os.path.basename(path)
        match = filename_re.match(basename)
        if match is None:
            raise ValueError('filename {} does not match required pattern')

        tract, patch_x, patch_y, index = match.groups()

        self.path = path
        self.tract = int(tract)
        self.patch = '{},{}'.format(patch_x, patch_y)
        self.index = int(index)
        self._handle = None
        self._keys = None
        self._len = None 
Example #11
Source File: photoz_magerr.py    From gcr-catalogs with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, path, filename_pattern=None):

        if isinstance(filename_pattern, re.Pattern): # pylint: disable=no-member
            filename_re = filename_pattern
        else:
            filename_re = re.compile(filename_pattern)

        basename = os.path.basename(path)
        match = filename_re.match(basename)
        if match is None:
            raise ValueError('filename {} does not match required pattern')

        z_block_lower, pixelid = tuple(map(int, match.groups()))
        self.z_block_lower = int(z_block_lower)
        self.healpix_pixel = int(pixelid)
        self.path = path
        self._handle = None
        self._keys = None
        self._len = None 
Example #12
Source File: trace.py    From myia with MIT License 6 votes vote down vote up
def on(self, pattern, fn):
        """Register a function to trigger on a certain pattern.

        The pattern can be an event name or a glob.

        * `**` in a pattern matches any character sequence including
          the / delimiter

            * `/**/` can also match `/`

        * `*` matches any character sequence except /
        * A pattern that does not start with `/` is equivalent to the same
          pattern prepended with `/**/`, e.g. `apple` is equivalent to
          `/**/apple`
        """
        if not isinstance(pattern, re.Pattern):
            pattern = glob_to_regex(pattern)
        self.listeners.append((pattern, fn)) 
Example #13
Source File: __init__.py    From gkeepapi with MIT License 6 votes vote down vote up
def findLabel(self, query, create=False):
        """Find a label with the given name.

        Args:
            name (Union[_sre.SRE_Pattern, str]): A str or regular expression to match against the name.
            create (bool): Whether to create the label if it doesn't exist (only if name is a str).

        Returns:
            Union[gkeepapi.node.Label, None]: The label.
        """
        is_str = isinstance(query, six.string_types)
        name = None
        if is_str:
            name = query
            query = query.lower()

        for label in self._labels.values():
            # Match the label against query, which may be a str or Pattern.
            if (is_str and query == label.name.lower()) or \
                (isinstance(query, Pattern) and query.search(label.name)):
                return label

        return self.createLabel(name) if create and is_str else None 
Example #14
Source File: irc.py    From localslackirc with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, s: asyncio.streams.StreamWriter, sl_client: Union[slack.Slack], nouserlist: bool, autojoin: bool, provider: Provider):
        self.nick = b''
        self.username = b''
        self.realname = b''
        self.parted_channels: Set[bytes] = set()
        self.hostname = gethostname().encode('utf8')

        self.provider = provider
        self.s = s
        self.sl_client = sl_client
        self.nouserlist = nouserlist
        self.autojoin = autojoin
        self._usersent = False # Used to hold all events until the IRC client sends the initial USER message
        self._held_events: List[slack.SlackEvent] = []
        self._magic_users_id = 0
        self._magic_regex: Optional[re.Pattern] = None

        if self.provider == Provider.SLACK:
            self.substitutions = _SLACK_SUBSTITUTIONS
        else:
            self.substitutions = [] 
Example #15
Source File: parsers.py    From plantcv with MIT License 6 votes vote down vote up
def _parse_filename(filename, delimiter, regex):
    """Parse the input filename and return a list of metadata.

    Args:
        filename:   Filename to parse metadata from
        delimiter:  Delimiter character to split the filename on
        regex:      Compiled regular expression pattern to process file with

    :param filename: str
    :param delimiter: str
    :param regex: re.Pattern
    :return metadata: list
    """

    # Split the filename on delimiter if it is a single character
    if len(delimiter) == 1:
        metadata = filename.split(delimiter)
    else:
        metadata = re.search(regex, filename)
        if metadata is not None:
            metadata = list(metadata.groups())
        else:
            metadata = []
    return metadata
########################################### 
Example #16
Source File: cli.py    From docstr_coverage with MIT License 6 votes vote down vote up
def do_include_filepath(filepath: str, exclude_re: Optional["re.Pattern"]) -> bool:
    """Determine whether `filepath` should be included in docstring search

    Parameters
    ----------
    filepath: String
        Filepath to match with `exclude_re`. If extension is not ".py", it will be excluded
    exclude_re: re.Pattern, or None
        Pattern for files to be excluded. If None, `exclude_re` is ignored

    Returns
    -------
    Boolean
        True if `filepath` should be searched, else False"""
    if not filepath.endswith(".py"):
        return False
    if exclude_re is not None:
        return not exclude_re.match(filepath)
    return True 
Example #17
Source File: yara_rules_parser.py    From connectors with Apache License 2.0 5 votes vote down vote up
def _match_regex(regex: re.Pattern, string) -> Optional[str]:
        match = regex.search(string)
        if match:
            return match.group(1)
        else:
            return None 
Example #18
Source File: case.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def assertRaisesRegex(self, expected_exception, expected_regex,
                          *args, **kwargs):
        """Asserts that the message in a raised exception matches a regex.

        Args:
            expected_exception: Exception class expected to be raised.
            expected_regex: Regex (re.Pattern object or string) expected
                    to be found in error message.
            args: Function to be called and extra positional args.
            kwargs: Extra kwargs.
            msg: Optional message used in case of failure. Can only be used
                    when assertRaisesRegex is used as a context manager.
        """
        context = _AssertRaisesContext(expected_exception, self, expected_regex)
        return context.handle('assertRaisesRegex', args, kwargs) 
Example #19
Source File: quick_lambdas.py    From moshmosh with MIT License 5 votes vote down vote up
def __init__(self, pattern: 're.Pattern', mk_arg): # re.Pattern might not found
        self.mk_arg = mk_arg
        self.pattern = pattern
        self.max_arg_index = -1 
Example #20
Source File: selector_builder.py    From nerodia with MIT License 5 votes vote down vote up
def _process_attribute(self, key, value):
        if isinstance(value, Pattern):
            return self._predicate_conversion(key, value)
        else:
            return self._predicate_expression(key, value) 
Example #21
Source File: series.py    From modin with Apache License 2.0 5 votes vote down vote up
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 #22
Source File: series.py    From modin with Apache License 2.0 5 votes vote down vote up
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 #23
Source File: series.py    From modin with Apache License 2.0 5 votes vote down vote up
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 #24
Source File: forms.py    From nyaa with GNU General Public License v3.0 5 votes vote down vote up
def register_email_blacklist_validator(form, field):
    email_blacklist = app.config.get('EMAIL_BLACKLIST', [])
    email = field.data.strip()
    validation_exception = StopValidation('Blacklisted email provider')

    for item in email_blacklist:
        if isinstance(item, re.Pattern):
            if item.search(email):
                raise validation_exception
        elif isinstance(item, str):
            if item in email.lower():
                raise validation_exception
        else:
            raise Exception('Unexpected email validator type {!r} ({!r})'.format(type(item), item))
    return True 
Example #25
Source File: test_cli.py    From docstr_coverage with MIT License 5 votes vote down vote up
def test_collect_filepaths(paths: List[str], exclude: str, expected: List[str]):
    """Test that :func:`docstr_coverage.cli.collect_filepaths` includes correct filepaths

    Parameters
    ----------
    paths: List
        Path(s) to directory/file
    exclude: String
        Pattern for filepaths to exclude
    expected: List
        Expected list of filepaths to include in search"""
    actual = collect_filepaths(*paths, follow_links=False, exclude=exclude)
    assert actual == expected 
Example #26
Source File: case.py    From android_universal with MIT License 5 votes vote down vote up
def assertRaisesRegex(self, expected_exception, expected_regex,
                          *args, **kwargs):
        """Asserts that the message in a raised exception matches a regex.

        Args:
            expected_exception: Exception class expected to be raised.
            expected_regex: Regex (re.Pattern object or string) expected
                    to be found in error message.
            args: Function to be called and extra positional args.
            kwargs: Extra kwargs.
            msg: Optional message used in case of failure. Can only be used
                    when assertRaisesRegex is used as a context manager.
        """
        context = _AssertRaisesContext(expected_exception, self, expected_regex)
        return context.handle('assertRaisesRegex', args, kwargs) 
Example #27
Source File: test_cli.py    From docstr_coverage with MIT License 5 votes vote down vote up
def test_do_include_filepath(filepath: str, exclude_re: Optional[str], expected: bool):
    """Test that :func:`docstr_coverage.cli.do_include_filepath` includes correct filepaths

    Parameters
    ----------
    filepath: String
        Filepath to match with `exclude_re`
    exclude_re: String, or None
        Pattern to check against `filepath`. Indirectly parametrized to be `re.Pattern` or None
    expected: Boolean
        Expected response to whether `filepath` should be included"""
    actual = do_include_filepath(filepath, exclude_re)
    assert actual is expected 
Example #28
Source File: test_cli.py    From docstr_coverage with MIT License 5 votes vote down vote up
def exclude_re(request) -> "re.Pattern":
    """Indirectly parametrized fixture that expects a string or None as input"""
    pattern = getattr(request, "param", None)
    return re.compile(r"{}".format(pattern)) if pattern else None 
Example #29
Source File: select.py    From nerodia with MIT License 5 votes vote down vote up
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 #30
Source File: core.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def transform_version(self, version, options):
        """
        Transforms a version like `1.2.3-rc.4+5` to its constituent parts. In all cases,
        the metadata names `version.raw` and `version.scheme` will be collected.

        If a `scheme` is defined then it will be looked up from our known schemes. If no
        scheme is defined then it will default to `semver`. The supported schemes are:

        - `regex` - A `pattern` must also be defined. The pattern must be a `str` or a pre-compiled
          `re.Pattern`. Any matching named subgroups will then be sent as `version.<GROUP_NAME>`. In this case,
          the check name will be used as the value of `version.scheme` unless `final_scheme` is also set, which
          will take precedence.
        - `parts` - A `part_map` must also be defined. Each key in this mapping will be considered
          a `name` and will be sent with its (`str`) value.
        - `semver` - This is essentially the same as `regex` with the `pattern` set to the standard regular
          expression for semantic versioning.

        Taking the example above, calling `#!python self.set_metadata('version', '1.2.3-rc.4+5')` would produce:

        | name | value |
        | --- | --- |
        | `version.raw` | `1.2.3-rc.4+5` |
        | `version.scheme` | `semver` |
        | `version.major` | `1` |
        | `version.minor` | `2` |
        | `version.patch` | `3` |
        | `version.release` | `rc.4` |
        | `version.build` | `5` |
        """
        scheme, version_parts = parse_version(version, options)
        if scheme == 'regex' or scheme == 'parts':
            scheme = options.get('final_scheme', self.check_name)

        data = {'version.{}'.format(part_name): part_value for part_name, part_value in iteritems(version_parts)}
        data['version.raw'] = version
        data['version.scheme'] = scheme

        return data