如何在 Python 中使用正則表示式匹配字串結尾?\n\n


Python 中的正則表示式是一組字元,允許您使用搜索模式查詢字串或一組字串。RegEx 是正則表示式的另一個術語。

正則表示式在 Python 中使用re包進行處理。

要使用正則表示式在 Python 中匹配字串結尾,我們使用^/w+$正則表示式。

這裡,

  • $表示以...結尾。

  • /w返回一個匹配項,其中字串包含任何單詞字元(az、AZ、09 和下劃線字元)。

  • +表示一個或多個字元的出現。

使用 re.search() 方法

在以下示例程式碼中,我們匹配單詞skills,它位於字串“tutorialspoint is a great platform to enhance your skills”的末尾。

我們首先匯入正則表示式模組。

import re

然後,我們使用了從 re 模組匯入的search()函式。Python 中的此re.search()函式搜尋字串以進行匹配,如果存在任何匹配項,則返回匹配物件。group()方法用於返回匹配的字串部分。

示例

import re s = 'tutorialspoint is a great platform to enhance your skills' result = re.search(r'\w+$', s) print(result.group())

輸出

執行上述程式後,將獲得以下輸出。

skills

使用 re.findall() 方法

Python 中的 findall(pattern, string) 方法查詢字串中模式的每次出現。當您使用模式“\w+$”時,美元符號 ($) 保證您只匹配字串末尾的 Python 單詞。

示例

import re text = 'tutorialspoint is a great platform to enhance your skills' result = re.findall(r'\w+$', text) print(result)

輸出

以下是上述程式碼的輸出

['skills']

更新於: 2022-11-08

13K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告