Python中的正則表達(dá)式

正則表達(dá)式使用步驟

1. 用import re導(dǎo)入正則表達(dá)式

2. 用re.compile()函數(shù)創(chuàng)建一個(gè)Regex對(duì)象

3. 向Regex對(duì)象的search()方法傳入想查找的字符串,它返回一個(gè)Match對(duì)象

4. 調(diào)用Match對(duì)象的group方法,返回實(shí)際匹配文本的字符串

import re

phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')

mo = phoneNumRegex.search('My number is 415-332-9870')

print('Phone number found: '+ mo.group())

創(chuàng)建分組

添加括號(hào)將在正則表達(dá)式中創(chuàng)建“分組”:(\d\d\d)-(\d\d\d-\d\d\d\d)

然后可以使用group()匹配對(duì)象方法,從一個(gè)分組獲取匹配的文本。向group方法傳入0或不傳入?yún)?shù),將返回整個(gè)文本,向group方法傳入整數(shù)1或2,就可以取得匹配文本的不同部分。

group1 = mo.group(1)

group2 = mo.group(2)

print(group1)

print(group2)

一次獲得所有的分組,使用groups()方法:

areaCode, mainNumber = mo.groups()

print(areaCode)

print(mainNumber)

不同特殊字符的用法:

“|”希望匹配許多表達(dá)式中的一個(gè)時(shí),

正則表達(dá)式r'Batman|Tina Fey'將匹配Batman或者Tina Fey, 如果它們都出現(xiàn)在被查找的字符串中,第一次出現(xiàn)的匹配文本將作為Match對(duì)象返回。

heroRegex = re.compile(r'Batman|Tina Fey')

mo1 = heroRegex.search("Batman and Tina Fey")

print(mo1.group()) ?# 返回Batman

mo2 = heroRegex.search("Tina Fey and Batman")

print(mo2.group()) ?# 返回Tina Fey

"|"中的括號(hào)分組使用

batRegex = re.compile(r'Bat(man|mobile|copter|bat)')

mo = batRegex.search("Batmobile lost a wheel.")

print(mo.group(1)) ?# 匹配括號(hào)中出現(xiàn)的第一個(gè)字符

print(mo.group()) # 匹配整個(gè)對(duì)應(yīng)字符

"?"實(shí)現(xiàn)可選匹配,匹配這個(gè)問號(hào)之前的分組零次或一次

batRegex = re.compile(r'Bat(wo)?man')

mo1 = batRegex.search("The adventures of Batman.")

mo2 = batRegex.search("The adventures of Batwoman.")

print(mo1.group()) ?# 返回Batman

print(mo2.group()) ?# 返回Batwoman

"*"實(shí)現(xiàn)匹配零次或多次

batRegex = re.compile(r'Bat(wo)*man')

mo1 = batRegex.search("The adventures of Batman.")

mo2 = batRegex.search("The adventures of Batwowowowoman.")

mo3 = batRegex.search("The adventures of Batwoman.")

print(mo1.group())

print(mo2.group())

print(mo3.group())

“+”匹配一次或多次

batRegex = re.compile(r'Bat(wo)+man')

mo1 = batRegex.search("The adventures of Batman.")

mo2 = batRegex.search("The adventures of Batwowowowoman.")

mo3 = batRegex.search("The adventures of Batwoman.")

print(mo1 == None) ?# 返回True 沒有匹配結(jié)果

print(mo2.group())

print(mo3.group())

“{n}”匹配出現(xiàn)的次數(shù)

haRegex = re.compile(r'(Ha){3}')

mo1 = haRegex.search('HaHaHa')

print(mo1.group())

mo2 = haRegex.search('Ha')

print(mo2 == None)

貪心和非貪心匹配

在次數(shù)后面加上?表示非貪心匹配,如{3,5}?則只匹配3次。

greedyHaRegex = re.compile(r'(Ha){3,5}')

nongreedyHaRegex = re.compile(r'(Ha){3,5}?')

mo1 = greedyHaRegex.search('HaHaHaHaHa')

print(mo1.group())

mo2 = nongreedyHaRegex.search('HaHaHaHaHa')

print(mo2.group())

findall()方法

1. 如果調(diào)用在一個(gè)沒有分組的正則表達(dá)式上,findall()將返回一個(gè)匹配字符串的列表

2. 如果調(diào)用在一個(gè)有分組的正則表達(dá)式上,findall()將返回一個(gè)字符串的元組列表

phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')

number_str = "Cell:415-555-9999 Work:212-555-0000"

mo = phoneNumRegex.findall(number_str)

print(mo)

phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')

number_str = "Cell:415-555-9999 Work:212-555-0000"

mo1 = phoneNumRegex.findall(number_str)

print(mo1)

開始和結(jié)束匹配

# ^ and $

beginsWithHello = re.compile(r'^Hello')

mo = beginsWithHello.search("Hello World")

print(mo.group())

endWithNumber = re.compile(r'\d$')

mo1 = endWithNumber.search("Your age is 23")

print(mo1.group())

.*匹配所有字符

nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)')

mo2 = nameRegex.search("First Name: Al Last Name: Sweigart")

print(mo2.group())

re.I傳入compile第二個(gè)參數(shù),忽略大小寫

robocop = re.compile(r'robocop',re.I)

mo3 = robocop.search('RoBocop is part man, part machine, all cop')

mo4 = robocop.search('ROBOCOP is part man, part machine')

print(mo3.group())

print(mo4.group())

sub()方法

namesRegex = re.compile(r'Agent \w+')

mo5 = namesRegex.sub('CENSORED','Agent Alice gave the secret to Agent Bob.')

print(mo5)

agentNamesRegex = re.compile(r'Agent (\w)(\w*)')

mo6 = agentNamesRegex.sub(r'*\2','Agent Alice told Agent Carol that Agent Eve knew Agent Bob was a double agent.')

print(mo6)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • re模塊的高級(jí)應(yīng)用 search 執(zhí)行正則表達(dá)式搜索并且在搜索結(jié)束后返回所匹配到的串,只返回第一次匹配到的結(jié)果求出...
    偉大的洪立閱讀 332評(píng)論 0 0
  • 為什么要使用正則表達(dá)式 在軟件開發(fā)過(guò)程中,經(jīng)常涉及到大量的關(guān)鍵字等各種字符串的操作,使用正則表達(dá)式能很大簡(jiǎn)化開發(fā)的...
    偉大的洪立閱讀 405評(píng)論 0 0
  • 前言 正則表達(dá)式作為一種字符串匹配邏輯,在此不做贅述。本文的重點(diǎn),并不是正則表達(dá)式,而是在Python中使用正則表...
    oceanLong閱讀 220評(píng)論 0 0
  • 何所謂正則表達(dá)式?個(gè)人理解就是文本搜索的一種規(guī)則。那么正則表達(dá)式就需要解決下面的問題 規(guī)則如何表示 規(guī)則如何使用 ...
    閃電俠悟空閱讀 241評(píng)論 0 0
  • Runtime 1. objc在向一個(gè)對(duì)象發(fā)送消息時(shí),發(fā)生了什么? 2. 什么時(shí)候會(huì)報(bào)unrecognized ...
    波妞和醬豆子閱讀 2,120評(píng)論 0 15

友情鏈接更多精彩內(nèi)容