當前位置: 首頁>>代碼示例>>Python>>正文


Python re.Match方法代碼示例

本文整理匯總了Python中re.Match方法的典型用法代碼示例。如果您正苦於以下問題:Python re.Match方法的具體用法?Python re.Match怎麽用?Python re.Match使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在re的用法示例。


在下文中一共展示了re.Match方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_regex01

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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) 
開發者ID:HaoZhang95,項目名稱:Python24,代碼行數:24,代碼來源:basic01.py

示例2: test_find_token_valid_match

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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) 
開發者ID:python-discord,項目名稱:bot,代碼行數:22,代碼來源:test_token_remover.py

示例3: _has_watch_regex_match

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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 
開發者ID:python-discord,項目名稱:bot,代碼行數:20,代碼來源:filtering.py

示例4: _processLength

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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:] 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:24,代碼來源:basic.py

示例5: match_splitter

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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 
開發者ID:mkaraniya,項目名稱:BotHub,代碼行數:23,代碼來源:sed.py

示例6: construct_resource_links

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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')}"
        } 
開發者ID:limitedeternity,項目名稱:foxford_courses,代碼行數:23,代碼來源:fns.py

示例7: search_in_comments

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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 
開發者ID:packit-service,項目名稱:ogr,代碼行數:20,代碼來源:utils.py

示例8: unmatched

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start]+match.string[end:] 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:6,代碼來源:cookiejar.py

示例9: test_find_token_invalid_matches

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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) 
開發者ID:python-discord,項目名稱:bot,代碼行數:13,代碼來源:test_token_remover.py

示例10: get_name_matches

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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) 
開發者ID:python-discord,項目名稱:bot,代碼行數:8,代碼來源:filtering.py

示例11: sub_clyde

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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 
開發者ID:python-discord,項目名稱:bot,代碼行數:17,代碼來源:messages.py

示例12: test_num_or_match_should_return_regex_match_when_compare_strings

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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) 
開發者ID:dunossauro,項目名稱:splitty,代碼行數:7,代碼來源:test_splitty.py

示例13: CompareExpression

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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) 
開發者ID:log2timeline,項目名稱:plaso,代碼行數:13,代碼來源:expression_parser.py

示例14: _truncate_float

# 需要導入模塊: import re [as 別名]
# 或者: from re import Match [as 別名]
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 '' 
開發者ID:Qiskit,項目名稱:qiskit-terra,代碼行數:14,代碼來源:latex.py


注:本文中的re.Match方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。