自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python正則表達式:十個正則表達式應用實例

開發(fā)
在Python中,通過re模塊,我們可以輕松地進行模式匹配、搜索、替換等操作。本文將通過15個實例,從基礎到進階,讓你掌握Python正則表達式的實用技巧。

正則表達式,常被稱為“regex”,是處理文本數(shù)據(jù)的超級工具。在Python中,通過re模塊,我們可以輕松地進行模式匹配、搜索、替換等操作。本文將通過15個實例,從基礎到進階,讓你掌握Python正則表達式的實用技巧。

實例1:基本匹配

目標:找出字符串中的所有單詞。

import re

text = "Hello, world! Welcome to Python programming."
words = re.findall(r'\b\w+\b', text)
print(words) # 輸出: ['Hello', 'world', 'Welcome', 'to', 'Python', 'programming']

解釋:\b表示單詞邊界,\w+匹配一個或多個字母數(shù)字字符。

實例2:數(shù)字提取

目標:提取電話號碼(假設格式為XXX-XXXX-XXXX)。

phone_numbers = "My number is 123-456-7890."
matches = re.findall(r'\d{3}-\d{4}-\d{4}', phone_numbers)
print(matches) # 輸出: ['123-456-7890']

技巧:\d代表數(shù)字,{n}指定重復次數(shù)。

實例3:郵箱地址匹配

目標:從一段文本中找出所有郵箱地址。

text_email = "Contact us at info@example.com or support@example.co.uk."
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text_email)
print(emails) # 輸出: ['info@example.com', 'support@example.co.uk']

注意:郵箱地址的正則表達式相對復雜,但能匹配大多數(shù)格式。

實例4:替換操作

目標:將所有的“Python”替換為“Python編程”。

text_replace = "Python is fun. I love Python."
updated_text = re.sub(r'Python', 'Python編程', text_replace)
print(updated_text) # 輸出: Python編程 is fun. I love Python編程.

功能:re.sub()用于替換匹配到的內(nèi)容。

實例5:貪婪與非貪婪匹配

目標:提取HTML標簽間的文本,考慮非貪婪匹配。

html_text = "<p>Hello, world!</p><div>Welcome!</div>"
content = re.findall(r'<[^>]*>(.*?)</[^>]*>', html_text, re.DOTALL)
print(content) # 輸出: ['Hello, world!', 'Welcome!']

關鍵:?使匹配非貪婪,re.DOTALL使.匹配包括換行在內(nèi)的所有字符。

實例6:分組與引用

目標:提取網(wǎng)址的協(xié)議和主機部分。

url = "https://www.example.com/path"
protocol, host = re.search(r'^(https?://)([^/]+)', url).groups()
print(protocol, host) # 輸出: https:// www.example.com

解析:圓括號定義了分組,\1和\2引用分組內(nèi)容。

實例7:重復模式

目標:匹配連續(xù)的數(shù)字序列。

sequence = "123456789012345"
consecutive_digits = re.findall(r'(\d)\1+', sequence)
print(consecutive_digits) # 輸出: ['1', '2', '3', '4', '5']

技巧:\1+匹配至少一次前面的分組。

實例8:否定預查

目標:查找不以數(shù)字開頭的單詞。

text = "3 apples, no bananas, 10 oranges."
words = re.findall(r'\b(?!\d)\w+\b', text)
print(words) # 輸出: ['apples,', 'no', 'bananas,', 'oranges.']

解釋:(?!...)是負向前瞻,確保其后不匹配特定模式。

實例9:條件匹配

目標:區(qū)分郵箱的教育和商業(yè)賬號。

email_text = "edu@example.edu biz@example.biz"
edu_or_biz = re.findall(r'(\w+@)(edu|biz)\.', email_text)
print(edu_or_biz) # 輸出: [('edu@example.', 'edu'), ('biz@example.', 'biz')]

使用:通過條件分支實現(xiàn)特定匹配。

實例10:全局標志

目標:大小寫不敏感的搜索。

mixed_case = "Python is fun. PYTHON too!"
result = re.findall(r'python', mixed_case, re.IGNORECASE)
print(result) # 輸出: ['Python', 'PYTHON']

標志:re.IGNORECASE忽略大小寫。

實戰(zhàn)案例:清理CSV文件中的無效數(shù)據(jù)

場景:從CSV文件中移除非數(shù)字的手機號碼記錄。

import csv
import re

# 假設手機號碼應為10位數(shù)字
pattern = re.compile(r'^\d{10}$')

with open('phone_numbers.csv', 'r') as file:
    reader = csv.reader(file)
    cleaned_data = []
    for row in reader:
        if pattern.match(row[0]):  # 假設手機號碼在第一列
            cleaned_data.append(row)

# 將清洗后的數(shù)據(jù)保存到新文件
with open('cleaned_phone_numbers.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(cleaned_data)

分析:此案例展示了如何結合正則表達式和文件操作來處理實際問題,確保數(shù)據(jù)質(zhì)量。

通過上述實例和實戰(zhàn)案例,你已經(jīng)掌握了Python正則表達式的基礎到進階應用。

責任編輯:趙寧寧 來源: 手把手PythonAI編程
相關推薦

2018-09-27 15:25:08

正則表達式前端

2020-09-04 09:16:04

Python正則表達式虛擬機

2021-01-27 11:34:19

Python正則表達式字符串

2009-09-16 16:22:04

正則表達式匹配

2010-03-25 18:25:36

Python正則表達式

2011-07-11 12:33:30

JAVA

2009-09-16 16:01:57

PHP正則表達式正則表達式的應用

2009-02-18 09:48:20

正則表達式Java教程

2009-09-16 18:19:34

正則表達式組

2011-06-02 12:34:16

正則表達式

2017-05-12 10:47:45

Linux正則表達式程序基礎

2019-07-17 15:45:47

正則表達式字符串前端

2022-03-28 06:19:14

正則表達式開發(fā)

2016-11-10 16:21:22

Java 正則表達式

2022-01-04 11:35:03

Linux Shel正則表達式Linux

2023-09-13 08:12:45

2009-09-16 17:15:57

正則表達式引擎

2010-03-01 15:51:59

Python則表達式

2010-03-11 08:55:45

python正則表達式

2019-12-10 10:40:57

Python正則表達式編程語言
點贊
收藏

51CTO技術棧公眾號