Python re模塊學習


這是re模塊與正則的結合

re模塊提供的函數

1.match  嘗試在字符串的開頭應用該模式,返回匹配對象,如果沒有找到匹配,則為None。

1 import re
2 
3 str1 = "Why are you keeping this curiosity door locked?"
4 res = re.match('\w+y', str1)
5 print(res)

如果要獲取匹配的值則需要調用group()方法:

print(res.group())

2. fullmatch  表示匹配全部字符串,返回匹配對象,如果沒有找到匹配,則返回None。

 

import re

str1 = "Why are you keeping this curiosity door locked?"
res = re.fullmatch('\w+y', str1)
print(res)

import re

str1 = "Why"
res = re.fullmatch('\w+y', str1)
print(res)

3.search  匹配到第一個符合的字符串就會停止,返回匹配對象,如果沒有找到匹配,則返回None。

 

import re

str1 = "Why are you keeping this curiosity door locked? looking foreword"
res = re.search('\w+g', str1)
print(res)
print(res.group())

match  就相當於 re.search('^RE', string) (從頭開始去匹配)

4. findall 匹配字符串中所有符合的 ,返回匹配對象(列表),如果沒有找到匹配,則返回None。

 

import re

str1 = "Why are you keeping this curiosity door locked? looking foreword"
res = re.findall('\w+g', str1)
print(res)

5. sub 把匹配到的字符串再用給的字符替換,然后返回新的字符串

sub(pattern, repl, string, count=0, flags=0)
import re

str1 = "Why are you keeping this curiosity door locked? looking foreword"
res = re.sub('ing', 'ed', str1)
print(res)

import re

str1 = "Why are you keeping this curiosity door locked? looking foreword"
res = re.subn('ing', 'ed', str1)
print(res)

subn則會告訴你替換了多少處(返回的是一個元祖)

6. split  相當於 字符串的split的用法, 返回切割后的列表

import re

str1 = "Why are you keeping this curiosity door locked? looking foreword"
res = re.split('e', str1)
print(res)

可以把(RE)用括號括起來就可以把用來切割的 字符串也包含進列表中

import re

str1 = "Why are you keeping this curiosity door locked? looking foreword"
res = re.split('(\we)', str1)
print(res)

 

7. compile 先把正則編譯,如果需要很多匹配的字符串都用到同一個正則表達式,則可以用compile先把正則編譯好,可以節約時間

8.finditer  可以從匹配到的列表里一個一個的獲取到數據,經常與compile連用處理比較多的數據

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM