如何在Python中使用正則表示式匹配任何非數字字元?


正則表示式是一組字元,允許您使用搜索模式查詢字串或一組字串。RegEx是正則表示式的另一個名稱。Python中的re模組用於處理正則表示式。

在本文中,我們將探討如何使用正則表示式在Python中提取非數字字元。我們使用\D+正則表示式在Python中從字串中獲取非數字字元。

其中:

  • \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

更新於:2022年11月8日

5K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告