Python re.RegexObject() Examples

The following are 8 code examples of re.RegexObject(). 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: fastdupes.py    From fastdupes with GNU General Public License v2.0 6 votes vote down vote up
def multiglob_compile(globs, prefix=False):
    """Generate a single "A or B or C" regex from a list of shell globs.

    :param globs: Patterns to be processed by :mod:`fnmatch`.
    :type globs: iterable of :class:`~__builtins__.str`

    :param prefix: If ``True``, then :meth:`~re.RegexObject.match` will
        perform prefix matching rather than exact string matching.
    :type prefix: :class:`~__builtins__.bool`

    :rtype: :class:`re.RegexObject`
    """
    if not globs:
        # An empty globs list should only match empty strings
        return re.compile('^$')
    elif prefix:
        globs = [x + '*' for x in globs]
    return re.compile('|'.join(fnmatch.translate(x) for x in globs)) 
Example #2
Source File: store.py    From pymailq with GNU General Public License v2.0 6 votes vote down vote up
def _is_mail_id(self, mail_id):
        """
        Check mail_id for a valid postfix queued mail ID.

        Validation is made using a :class:`re.RegexObject` stored in
        the :attr:`~PostqueueStore.mail_id_re` attribute of the
        :class:`~store.PostqueueStore` instance.

        :param str mail_id: Mail Postfix queue ID string
        :return: True or false
        :rtype: :func:`bool`
        """

        if self.mail_id_re.match(mail_id) is None:
            return False
        return True 
Example #3
Source File: trace_cmd.py    From workload-automation with Apache License 2.0 6 votes vote down vote up
def regex_body_parser(regex, flags=0):
    """
    Creates an event body parser form the specified regular expression (could be an
    ``re.RegexObject``, or a string). The regular expression should contain some named
    groups, as those will be extracted as the event attributes (unnamed groups and the
    reset of the match will be ignored).

    If the specified regex is a string, it will be compiled, in which case ``flags`` may
    be provided for the resulting regex object (see ``re`` standard module documentation).
    If regex is a pre-compiled object, flags will be ignored.

    """
    if isinstance(regex, str):
        regex = re.compile(regex, flags)

    def regex_parser_func(event, text):
        match = regex.search(text)
        if match:
            for k, v in match.groupdict().items():
                try:
                    event.fields[k] = int(v)
                except ValueError:
                    event.fields[k] = v

    return regex_parser_func 
Example #4
Source File: static_files_handler.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def __init__(self, root_path, url_map, url_pattern):
    """Initializer for StaticContentHandler.

    Args:
      root_path: A string containing the full path of the directory containing
          the application's app.yaml file.
      url_map: An appinfo.URLMap instance containing the configuration for this
          handler.
      url_pattern: A re.RegexObject that matches URLs that should be handled by
          this handler. It may also optionally bind groups.
    """
    super(StaticContentHandler, self).__init__(url_map, url_pattern)
    self._root_path = root_path 
Example #5
Source File: static_files_handler.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def __init__(self, root_path, url_map, url_pattern):
    """Initializer for StaticContentHandler.

    Args:
      root_path: A string containing the full path of the directory containing
          the application's app.yaml file.
      url_map: An appinfo.URLMap instance containing the configuration for this
          handler.
      url_pattern: A re.RegexObject that matches URLs that should be handled by
          this handler. It may also optionally bind groups.
    """
    super(StaticContentHandler, self).__init__(url_map, url_pattern)
    self._root_path = root_path 
Example #6
Source File: errorscan.py    From manheim-c7n-tools with Apache License 2.0 5 votes vote down vote up
def find_matching_func_names(filter, region_name, client=None):
        """
        Return a list of all Lambda functions with names that either start
        with ``filter`` (if ``filter`` is a string) or match ``filter`` (if
        filter is a ``re.RegexObject``).

        :param filter: lambda function name filter
        :type filter: ``str`` ``re.RegexObject``
        :param region_name: region name to run against
        :type region_name: str
        :param client: boto3 Lambda client, or None to create new
        :type client: ``boto3.client``
        :return: list of matching Lambda function names
        :rtype: list
        """
        if client is None:
            client = boto3.client('lambda', region_name=region_name)
        if isinstance(filter, type('')):
            filter = re.compile('^' + re.escape(filter) + '.*')
        logger.debug(
            'Finding Lambda function names matching: %s', filter.pattern
        )
        matches = []
        total = 0
        paginator = client.get_paginator('list_functions')
        for response in paginator.paginate():
            for func in response['Functions']:
                total += 1
                if not filter.match(func['FunctionName']):
                    continue
                matches.append(func['FunctionName'])
        logger.debug('Matched %d of %d Lambda functions', len(matches), total)
        return sorted(matches) 
Example #7
Source File: trace_cmd.py    From workload-automation with Apache License 2.0 5 votes vote down vote up
def sched_wakeup_parser(event, text):
    regex = re.compile(r'(?P<comm>\S+):(?P<pid>\d+) \[(?P<prio>\d+)\] success=(?P<success>\d) CPU:(?P<cpu>\d+)')
    parse_func = regex_body_parser(regex)
    return parse_func(event, text)


# Maps event onto the corresponding parser for its body text. A parser may be
# a callable with signature
#
#   parser(event, bodytext)
#
# a re.RegexObject, or a string (in which case it will be compiled into a
# regex). In case of a string/regex, its named groups will be used to populate
# the event's attributes. 
Example #8
Source File: pattern.py    From deepWordBug with Apache License 2.0 4 votes vote down vote up
def __init__(self, pattern, include=None):
		"""
		Initializes the :class:`RegexPattern` instance.

		*pattern* (:class:`unicode`, :class:`bytes`, :class:`re.RegexObject`,
		or :data:`None`) is the pattern to compile into a regular
		expression.

		*include* (:class:`bool` or :data:`None`) must be :data:`None`
		unless *pattern* is a precompiled regular expression (:class:`re.RegexObject`)
		in which case it is whether matched files should be included
		(:data:`True`), excluded (:data:`False`), or is a null operation
		(:data:`None`).

			.. NOTE:: Subclasses do not need to support the *include*
			   parameter.
		"""

		self.regex = None
		"""
		*regex* (:class:`re.RegexObject`) is the regular expression for the
		pattern.
		"""

		if isinstance(pattern, (unicode, bytes)):
			assert include is None, "include:{0!r} must be null when pattern:{1!r} is a string.".format(include, pattern)
			regex, include = self.pattern_to_regex(pattern)
			# NOTE: Make sure to allow a null regular expression to be
			# returned for a null-operation.
			if include is not None:
				regex = re.compile(regex)

		elif pattern is not None and hasattr(pattern, 'match'):
			# Assume pattern is a precompiled regular expression.
			# - NOTE: Used specified *include*.
			regex = pattern

		elif pattern is None:
			# NOTE: Make sure to allow a null pattern to be passed for a
			# null-operation.
			assert include is None, "include:{0!r} must be null when pattern:{1!r} is null.".format(include, pattern)

		else:
			raise TypeError("pattern:{0!r} is not a string, RegexObject, or None.".format(pattern))

		super(RegexPattern, self).__init__(include)
		self.regex = regex