如何在Python中使用正則表示式匹配字串末尾?
Python中的正則表示式是一組字元,允許您使用搜索模式來查詢字串或一組字串。RegEx是正則表示式的另一個術語。
在Python中,正則表示式使用re包進行處理。
為了使用正則表示式匹配Python字串的末尾,我們使用^/w+$正則表示式。
這裡:
$ 表示匹配字串結尾。
/w 匹配任何單詞字元(a-z、A-Z、0-9和下劃線)。
+ 表示一個或多個字元的出現。
使用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']
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP