如何在 Python 中使用正則表示式匹配任何非數字字元?\n\n
正則表示式是一組字元,允許您使用搜索模式查詢字串或一組字串。RegEx 是正則表示式的另一個名稱。Python 中的 re 模組用於處理正則表示式。
在本文中,我們研究瞭如何使用正則表示式在 Python 中提取非數字字元。我們使用 Python 中的\D+正則表示式從字串中獲取非數字字元。
其中,
- \D 返回不包含數字的匹配項。
- + 表示字元出現零次或多次。
使用 findall() 函式
在以下示例中,讓我們假設“2018Tutorials point”作為字串,我們需要消除 2018(這是一個數字)並必須提取 Tutorials point。
示例
在以下示例程式碼中,我們使用findAll()函式使用正則表示式在 Python 中匹配任何非數字字元。我們首先匯入正則表示式模組。
import re
然後,我們使用了從 re 模組匯入的findall()函式。
import re string = "2018Tutorials point" pattern= [r'\D+'] for i in pattern: match= re.findall(i, string) print(match)
re.findall()函式返回一個包含所有匹配項的列表,即包含非數字的字串列表。
輸出
執行上述程式後,將獲得以下輸出。
['Tutorials point']
示例
讓我們看另一個示例,其中一個字串包含多個數字。在這裡,我們假設“5 childrens 3 boys 2 girls”作為輸入短語。輸出應該返回所有包含非數字的字串。
import re string = "5 childrens 3 boys 2 girls" pattern= [r'\D+'] for i in pattern: match= re.findall(i, string) print(match)
輸出
執行上述程式後,將獲得以下輸出。
[' childrens ', ' boys ', ' girls']
使用 search() 函式
在以下程式碼中,我們匹配“5 childrens 3 boys 2 girls”字串,其中所有包含非數字的字串都被提取為“childrens boys girls”。
示例
在以下示例程式碼中,我們使用search()函式使用正則表示式在 Python 中匹配任何非數字字元。我們首先匯入正則表示式模組。
import re
然後,我們使用了從 re 模組匯入的search()函式來獲取所需的字串。此re.search()函式搜尋字串/段落以查詢匹配項,如果存在任何匹配項,則返回一個匹配物件。group()方法用於返回匹配的字串部分。
import re phrase = 'RANDOM 5childerns 3 boys 2 girls//' pattern = r'(?<=RANDOM).*?(?=//)' match = re.search(pattern, phrase) text = match.group(0) nonDigit = re.sub(r'\d', '', text) print(nonDigit)
輸出
執行上述程式後,將獲得以下輸出。
childerns boys girls
廣告