python3 re返回形式總結
我們在進行程序操作的時候,因為各種原因,需要通過不同的形式返回到之前的對象。不知道小伙伴們會幾種返回的函數(shù)方法呢?今天要介紹的是findall和finditer這一對小伙伴,它們在輸出的形式上有所不同。在這里小編先賣一個關子,想要知道答案的小伙伴,我們接著往下看。
findall(pattern, string, flags=0)
在字符串string中匹配所有符合正則表達式pattern的對象,并把這些對象通過列表list的形式返回。
import re
pattern = re.compile(r'\W+')
result1 = pattern.findall('hello world!')
result2 = pattern.findall('hello world!', 0, 7)
print(result1) #[' ', '!']
print(result2) #[' ']
finditer(pattern, string, flags=0)
在字符串string中匹配所有符合正則表達式pattern的對象,并把這些對象通過迭代器的形式返回。
import re
pattern = re.compile(r'\W+')
result = pattern.finditer('hello world!')
for r in result:
print(r)
# <re.Match object; span=(5, 6), match=' '>
# <re.Match object; span=(11, 12), match='!'>
Python3 Re常用方法
常用的功能函數(shù)包括:compile、search、match、split、findall(finditer)、sub(subn)
1.compile
- re.compile(pattern[, flags])
作用:把正則表達式語法轉化成正則表達式對象
flags定義包括:
- re.I:忽略大小寫
- re.L:表示特殊字符集 \w, \W, \b, \B, \s, \S 依賴于當前環(huán)境
- re.M:多行模式
- re.S:' . '并且包括換行符在內的任意字符(注意:' . '不包括換行符)
- re.U: 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依賴于 Unicode 字符屬性數(shù)據(jù)庫
2.search
- re.search(pattern, string[, flags])
作用:在字符串中查找匹配正則表達式模式的位置,返回 MatchObject 的實例,如果沒有找到匹配的位置,則返回 None。
3.match
- re.match(pattern, string[, flags])
- match(string[, pos[, endpos]])
作用:match() 函數(shù)只在字符串的開始位置嘗試匹配正則表達式,也就是只報告從位置 0 開始的匹配情況,
而 search() 函數(shù)是掃描整個字符串來查找匹配。如果想要搜索整個字符串來尋找匹配,應當用 search()。
到此這篇關于python3 re返回形式總結的文章就介紹到這了,更多相關python3 re有哪些返回形式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
用smtplib和email封裝python發(fā)送郵件模塊類分享
本文針對發(fā)郵件相關的操作進行了封裝,包括發(fā)送文本、HTML、帶附件的郵件,使用Python發(fā)郵件,主要用到smtplib和email兩個模塊,需要的朋友可以參考下2014-02-02
Python隨機生成數(shù)據(jù)后插入到PostgreSQL
本文主要介紹利用python的random庫生成隨機數(shù),然后插入到PostgreSQL數(shù)據(jù)庫中,有需要的可以參考學習。2016-07-07

