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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: _headersutil.py    From BruteXSS 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: cookielib.py    From canape 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 #12
Source File: scanid.py    From datman with Apache License 2.0 5 votes vote down vote up
def get_field(match, field, settings=None):
    """
    Find the value of an ID field, allowing for user specified changes.

    Args:
        match (:obj:`re.Match`): A match object created from a valid ID
        field (:obj:`str`): An ID field name. This is lower case and
            corresponds to the match groups of valid (supported) ID (e.g.
            study, site, subject)
        settings (:obj:`dict`, optional): User settings to specify fields that
            should be modified and how to modify them. See the settings
            description in :py:func:`parse` for more info. Defaults to None.

    Returns:
        str: The value of the field based on the re.Match groups and user
            settings.

    """

    if not settings or field.upper() not in settings:
        return match.group(field)

    mapping = settings[field.upper()]
    current_field = match.group(field)
    try:
        new_field = mapping[current_field]
    except KeyError:
        new_field = current_field

    return new_field 
Example #13
Source File: cookielib.py    From PokemonGo-DesktopMap 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 #14
Source File: cookielib.py    From unity-python 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 #15
Source File: cookiejar.py    From android_universal 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 #16
Source File: cookielib.py    From CTFCrackTools 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 #17
Source File: cookielib.py    From CTFCrackTools 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 #18
Source File: cookiejar.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 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: _headersutil.py    From yalih 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 #20
Source File: cookielib.py    From medicare-demo 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 #21
Source File: cookiejar.py    From Project-New-Reign---Nemesis-Main 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 #22
Source File: relib_test.py    From CrossHair with MIT License 5 votes vote down vote up
def test_match_properties(self) -> None:
        test_string = '01ab9'
        match = re.compile('ab').match('01ab9', 2, 4)
        assert match is not None
        self.assertEqual(match.span(), (2, 4))
        self.assertEqual(match.groups(), ())
        self.assertEqual(match.group(0), 'ab')
        self.assertEqual(match[0], 'ab')
        self.assertEqual(match.pos, 2)
        self.assertEqual(match.endpos, 4)
        self.assertEqual(match.lastgroup, None)
        self.assertEqual(match.string, '01ab9')
        self.assertEqual(match.re.pattern, 'ab')
        def f(s:str) -> Optional[re.Match]:
            '''
            pre: s == '01ab9'
            post: _.span() == (2, 4)
            post: _.groups() == ()
            post: _.group(0) == 'ab'
            post: _[0] == 'ab'
            post: _.pos == 2
            post: _.endpos == 4
            post: _.lastgroup == None
            post: _.string == '01ab9'
            post: _.re.pattern == 'ab'
            '''
            return re.compile('ab').match(s, 2, 4)
        self.assertEqual(*check_ok(f)) 
Example #23
Source File: relib_test.py    From CrossHair with MIT License 5 votes vote down vote up
def test_fullmatch_matches_whole_string(self) -> None:
        def f(s: str) -> Optional[re.Match]:
            '''
            pre: len(s) == 3
            post: implies(_, s[-1] == 'b')
            '''
            return re.compile('a+b+').fullmatch(s)
        self.assertEqual(*check_ok(f)) 
Example #24
Source File: relib_test.py    From CrossHair with MIT License 5 votes vote down vote up
def test_fullmatch_basic_ok(self) -> None:
        def f(s: str) -> Optional[re.Match]:
            '''
            pre: s == 'a'
            post: _
            '''
            return re.compile('a').fullmatch(s)
        self.assertEqual(*check_ok(f)) 
Example #25
Source File: relib_test.py    From CrossHair with MIT License 5 votes vote down vote up
def test_fullmatch_basic_fail(self) -> None:
        def f(s: str) -> Optional[re.Match]:
            ''' post: _ '''
            return re.compile('a').fullmatch(s)
        self.assertEqual(*check_fail(f)) 
Example #26
Source File: relib.py    From CrossHair with MIT License 5 votes vote down vote up
def __repr__(self):
        return f'<re.Match object; span={self.span()!r}, match={self.group()!r}>' 
Example #27
Source File: cookielib.py    From Splunking-Crime with GNU Affero 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: sed.py    From BotHub with Apache License 2.0 5 votes vote down vote up
def sub_matches(matches: list, original: str) -> Union[str, None]:
    """Iterate over all the matches whilst substituing the string.

    Args:
        matches (``list``):
            A list of :obj:`Match<re.match>` objects.
        original (``str``):
            The original string to use for substituion.

    Returns:
        ``str`` | ``None``:
            The final substitued string on success, None otherwise.
    """
    string = original
    total_subs = 0

    for match in matches:
        line, fr, to, fl = await match_splitter(match)
        try:
            count, flags = await resolve_flags(fl)
        except UnknownFlagError as f:
            exc = f"`Unknown flag:` `{f}`"
            return exc

        newStr = await substitute(fr,
                                  to,
                                  string,
                                  line=line,
                                  count=count,
                                  flags=flags)
        if newStr:
            string = newStr
            total_subs += 1

    if total_subs > 0:
        return string

    return 
Example #29
Source File: cookielib.py    From datafari 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 #30
Source File: check_package_versions_in_docs.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def _checks(
    file: Path, regex, extract_package_id_from_match: Callable[["re.Match"], PackageId],
):
    matches = regex.finditer(file.read_text())
    for match in matches:
        package_id = extract_package_id_from_match(match)
        if package_id not in ALL_PACKAGE_IDS:
            raise PackageIdNotFound(
                file, package_id, match, "Package {} not found.".format(package_id)
            )
        else:
            print(str(package_id), "OK!")