Python re.Match() Examples

The following are 30 code examples of re.Match(). 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: test_token_remover.py    From bot with MIT License 6 votes vote down vote up
def test_find_token_valid_match(self, token_re, token_cls, is_valid_id, is_valid_timestamp):
        """The first match with a valid user ID and timestamp should be returned as a `Token`."""
        matches = [
            mock.create_autospec(Match, spec_set=True, instance=True),
            mock.create_autospec(Match, spec_set=True, instance=True),
        ]
        tokens = [
            mock.create_autospec(Token, spec_set=True, instance=True),
            mock.create_autospec(Token, spec_set=True, instance=True),
        ]

        token_re.finditer.return_value = matches
        token_cls.side_effect = tokens
        is_valid_id.side_effect = (False, True)  # The 1st match will be invalid, 2nd one valid.
        is_valid_timestamp.return_value = True

        return_value = TokenRemover.find_token_in_message(self.msg)

        self.assertEqual(tokens[1], return_value)
        token_re.finditer.assert_called_once_with(self.msg.content) 
Example #2
Source File: filtering.py    From bot with MIT License 6 votes vote down vote up
def _has_watch_regex_match(text: str) -> Union[bool, re.Match]:
        """
        Return True if `text` matches any regex from `word_watchlist` or `token_watchlist` configs.

        `word_watchlist`'s patterns are placed between word boundaries while `token_watchlist` is
        matched as-is. Spoilers are expanded, if any, and URLs are ignored.
        """
        if SPOILER_RE.search(text):
            text = expand_spoilers(text)

        # Make sure it's not a URL
        if URL_RE.search(text):
            return False

        for pattern in WATCHLIST_PATTERNS:
            match = pattern.search(text)
            if match:
                return match 
Example #3
Source File: basic01.py    From Python24 with MIT License 6 votes vote down vote up
def test_regex01():

    # <re.Match object; span=(0, 3), match='终结者'>
    result1 = re.match(r"终结者", "终结者1")
    print(result1)

    # <re.Match object; span=(0, 4), match='终结者1'>
    result2 = re.match(r"终结者1", "终结者2")
    print(result2)

    # 有返回值group取出来自己期望的值
    if result2:
        print(result2.group())

    # \d
    result3 = re.match(r"终结者\d", "终结者1").group()
    result4 = re.match(r"终结者\d", "终结者2").group()
    result5 = re.match(r"终结者\d", "终结者3").group()

    print(result3)
    print(result4)
    print(result5) 
Example #4
Source File: basic.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _processLength(self, lengthMatch):
        """
        Processes the length definition of a netstring.

        Extracts and stores in C{self._expectedPayloadSize} the number
        representing the netstring size.  Removes the prefix
        representing the length specification from
        C{self._remainingData}.

        @raise NetstringParseError: if the received netstring does not
            start with a number or the number is bigger than
            C{self.MAX_LENGTH}.
        @param lengthMatch: A regular expression match object matching
            a netstring length specification
        @type lengthMatch: C{re.Match}
        """
        endOfNumber = lengthMatch.end(1)
        startOfData = lengthMatch.end(2)
        lengthString = self._remainingData[:endOfNumber]
        # Expect payload plus trailing comma:
        self._expectedPayloadSize = self._extractLength(lengthString) + 1
        self._remainingData = self._remainingData[startOfData:] 
Example #5
Source File: basic.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _processLength(self, lengthMatch):
        """
        Processes the length definition of a netstring.

        Extracts and stores in C{self._expectedPayloadSize} the number
        representing the netstring size.  Removes the prefix
        representing the length specification from
        C{self._remainingData}.

        @raise NetstringParseError: if the received netstring does not
            start with a number or the number is bigger than
            C{self.MAX_LENGTH}.
        @param lengthMatch: A regular expression match object matching
            a netstring length specification
        @type lengthMatch: C{re.Match}
        """
        endOfNumber = lengthMatch.end(1)
        startOfData = lengthMatch.end(2)
        lengthString = self._remainingData[:endOfNumber]
        # Expect payload plus trailing comma:
        self._expectedPayloadSize = self._extractLength(lengthString) + 1
        self._remainingData = self._remainingData[startOfData:] 
Example #6
Source File: sed.py    From BotHub with Apache License 2.0 6 votes vote down vote up
def match_splitter(match: re.Match) -> Tuple[str, str, str, str]:
    """Splits an :obj:`re.Match` to get the required attributes for substitution.
    Unescapes the slashes as well because this is Python.

    Args:
        match (:obj:`Match<re.match>`):
            Match object to split.

    Returns:
        (``str``, ``str``, ``str``, ``str``):
            A tuple of strings containing
            line, regexp, replacement and flags respectively.
    """
    li = match.group(1)
    fr = match.group(3)
    to = match.group(4) if match.group(4) else ''
    to = re.sub(r'\\/', '/', to)
    to = re.sub(r'(?<!\\)\\0', r'\g<0>', to)
    fl = match.group(5) if match.group(5) else ''

    return li, fr, to, fl 
Example #7
Source File: basic.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _processLength(self, lengthMatch):
        """
        Processes the length definition of a netstring.

        Extracts and stores in C{self._expectedPayloadSize} the number
        representing the netstring size.  Removes the prefix
        representing the length specification from
        C{self._remainingData}.

        @raise NetstringParseError: if the received netstring does not
            start with a number or the number is bigger than
            C{self.MAX_LENGTH}.
        @param lengthMatch: A regular expression match object matching
            a netstring length specification
        @type lengthMatch: C{re.Match}
        """
        endOfNumber = lengthMatch.end(1)
        startOfData = lengthMatch.end(2)
        lengthString = self._remainingData[:endOfNumber]
        # Expect payload plus trailing comma:
        self._expectedPayloadSize = self._extractLength(lengthString) + 1
        self._remainingData = self._remainingData[startOfData:] 
Example #8
Source File: fns.py    From foxford_courses with MIT License 6 votes vote down vote up
def construct_resource_links(self, erly_iframe_src: str) -> Dict:
        search_params: Dict = dict(
            parse.parse_qsl(
                parse.urlparse(erly_iframe_src).query
            )
        )

        if not {"conf", "access_token"}.issubset(set(search_params)):
            return {"fatal_error": "Iframe src search params structure is unknown"}

        webinar_id_match: Union[Match, None] = match(
            r"^webinar-(\d+)$", search_params.get("conf")
        )

        if not webinar_id_match:
            return {"fatal_error": "Unable to extract webinar id"}

        return {
            "video": f"https://storage.netology-group.services/api/v1/buckets/ms.webinar.foxford.ru/sets/{webinar_id_match[1]}/objects/mp4?access_token={search_params.get('access_token')}",
            "events": f"https://storage.netology-group.services/api/v1/buckets/meta.webinar.foxford.ru/sets/{webinar_id_match[1]}/objects/events.json?access_token={search_params.get('access_token')}"
        } 
Example #9
Source File: utils.py    From ogr with MIT License 6 votes vote down vote up
def search_in_comments(
    comments: List[Union[str, Comment]], filter_regex: str
) -> Optional[Match[str]]:
    """
    Find match in pull-request description or comments.

    :param comments: [str or PRComment]
    :param filter_regex: filter the comments' content with re.search
    :return: re.Match or None
    """
    pattern = re.compile(filter_regex)
    for comment in comments:
        if isinstance(comment, Comment):
            comment = comment.body
        re_search = pattern.search(comment)
        if re_search:
            return re_search
    return None 
Example #10
Source File: cookiejar.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #11
Source File: cookiejar.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #12
Source File: cookiejar.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #13
Source File: test_token_remover.py    From bot with MIT License 5 votes vote down vote up
def test_find_token_invalid_matches(self, token_re, token_cls, is_valid_id, is_valid_timestamp):
        """None should be returned if no matches have valid user IDs or timestamps."""
        token_re.finditer.return_value = [mock.create_autospec(Match, spec_set=True, instance=True)]
        token_cls.return_value = mock.create_autospec(Token, spec_set=True, instance=True)
        is_valid_id.return_value = False
        is_valid_timestamp.return_value = False

        return_value = TokenRemover.find_token_in_message(self.msg)

        self.assertIsNone(return_value)
        token_re.finditer.assert_called_once_with(self.msg.content) 
Example #14
Source File: filtering.py    From bot with MIT License 5 votes vote down vote up
def get_name_matches(name: str) -> List[re.Match]:
        """Check bad words from passed string (name). Return list of matches."""
        matches = []
        for pattern in WATCHLIST_PATTERNS:
            if match := pattern.search(name):
                matches.append(match) 
Example #15
Source File: messages.py    From bot with MIT License 5 votes vote down vote up
def sub_clyde(username: Optional[str]) -> Optional[str]:
    """
    Replace "e"/"E" in any "clyde" in `username` with a Cyrillic "е"/"E" and return the new string.

    Discord disallows "clyde" anywhere in the username for webhooks. It will return a 400.
    Return None only if `username` is None.
    """
    def replace_e(match: re.Match) -> str:
        char = "е" if match[2] == "e" else "Е"
        return match[1] + char

    if username:
        return re.sub(r"(clyd)(e)", replace_e, username, flags=re.I)
    else:
        return username  # Empty string or None 
Example #16
Source File: cookielib.py    From meddle with MIT License 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #17
Source File: cookielib.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #18
Source File: cookielib.py    From BinderFilter with MIT License 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #19
Source File: cookielib.py    From Computable with MIT License 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #20
Source File: cookielib.py    From oss-ftp with MIT License 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #21
Source File: cookiejar.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #22
Source File: test_splitty.py    From splitty with MIT License 5 votes vote down vote up
def test_num_or_match_should_return_regex_match_when_compare_strings(self):
        import re, sys, _sre

        if sys.version_info[1] >= 7:
            self.assertIsInstance(self.nom('sa', 'sa'), re.Match) 
Example #23
Source File: expression_parser.py    From plaso with Apache License 2.0 5 votes vote down vote up
def CompareExpression(self, expression):
    """Compares the token against an expression string.

    Args:
      expression (str): expression string.

    Returns:
      re.Match: the regular expression match object if the expression string
          matches the token or None if no match.
    """
    return self._regex.match(expression) 
Example #24
Source File: cookielib.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #25
Source File: cookiejar.py    From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #26
Source File: latex.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def _truncate_float(matchobj, ndigits=3):
    """Truncate long floats

    Args:
        matchobj (re.Match): contains original float
        ndigits (int): Number of digits to print
    Returns:
       str: returns truncated float
    """
    if matchobj.group(0):
        return '%.{}g'.format(ndigits) % float(matchobj.group(0))
    return '' 
Example #27
Source File: cookiejar.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #28
Source File: cookiejar.py    From Imogen with MIT License 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #29
Source File: cookiejar.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
Example #30
Source File: cookiejar.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:]