python中的re(正規表示式)
re是python對正規表示式的支援
1.re.match
作用:
嘗試從字串的開始匹配一個模式
re.match的函式原型為:
re.match(pattern, string, flags)
第一個引數是正規表示式,這裡為"(\w+)\s",如果匹配成功,則返回一個Match,否則返回一個None;
第二個參數列示要匹配的字串;
第三個引數是標緻位,用於控制正規表示式的匹配方式,如:是否區分大小寫,多行匹配等等。
例子:
text = "JGoodis a handsome boy, he is cool, clever, and so on..."
pa = re.compile("\w+")
ma = re.match(pa, text)
print ma.group()
輸出結果為:JGood,匹配了第一個單詞
2.re.search
作用:
函式會在字串內查詢模式匹配,只到找到第一個匹配然後返回,如果字串沒有匹配,則返回None。
re.search的函式原型為:
re.search(pattern, string,flags)。每個引數的含意與re.match一樣。
re.match與re.search的區別:
re.match只匹配字串的開始,如果字串開始不符合正規表示式,則匹配失敗,函式返回None;而re.search匹配整個字串,直到找到一個匹配。
例子:
text = " JGood is a handsome boy, he is cool, clever, and so on..." pa = re.compile("\w+") ma = re.search(pa, text)
輸出結果為:JGood,匹配了第一個單詞,之前空格沒有匹配
3.re.sub
作用:
用於替換字串中的匹配項
re.sub的函式原型為:
re.sub(pattern, repl, string, count)
其中第二個函式是替換後的字串;本例中為'-'
第四個引數指替換個數。預設為0,表示每個匹配項都替換。
例子:
text = " JGood is a handsome boy, he is cool, clever, and so on..." pa = re.compile("\w+([e|d])") su = re.sub(pa, "subText",text) print su
輸出結果為:subText is a subText boy, subText is cool, subTextr, subText so on... 將所有e和d結尾的單詞全部替換成subText
4. re.split
作用:
可以使用re.split來分割字串,如:re.split(r'\s+', text);將字串按空格分割成一個單詞列表。
例子:
text = "JGood is a handsome boy, he is cool, clever, and so on..." pa = re.compile("[ *, ]+") sp = re.split(pa, text) print sp
輸出結果為:['JGood', 'is', 'a', 'handsome', 'boy', 'he', 'is', 'cool','clever', 'and', 'so', 'on...'] 返回一個列表
5. re.findall
作用:
可以獲取字串中所有匹配的字串。如:re.findall(r'\w*oo\w*',text);獲取字串中,包含'oo'的所有單詞。
例子:
text = "JGood is a handsome boy, he is cool, clever, and so on..." pa = re.compile("\w+") fa = re.findall(pa, text) print fa
輸出結果為:['JGood', 'is', 'a', 'handsome', 'boy', 'he', 'is', 'cool','clever', 'and', 'so', 'on']
6. re.compile
作用:
可以把正規表示式編譯成一個正規表示式物件。可以把那些經常使用的正規表示式編譯成正規表示式物件,這樣可以提高一定的效率。
相關文章
- python中re模組的使用(正規表示式)Python
- Python 正規表示式 re 模組Python
- python re模組 正規表示式Python
- Python 之 RE(正規表示式)常用Python
- python正規表示式(re模組)Python
- python 關於正規表示式rePython
- Python正規表示式簡記和re庫Python
- Python爬蟲— 1.4 正規表示式:re庫Python爬蟲
- LeetCode-10. 正規表示式匹配(Python-re包)LeetCodePython
- python基礎 之 正規表示式和re模組Python
- python就業班----正規表示式及re應用Python就業
- python 正規表示式re常用操作符 使用方法 怎麼用re正規表示式表示一個IP地址:0-255Python
- 正規表示式re.compile的學習Compile
- 超詳細Python正規表示式操作指南(re使用),一Python
- Python——正規表示式Python
- python正規表示式Python
- Python 正規表示式Python
- Python:正規表示式Python
- Python爬蟲教程-19-資料提取-正規表示式(re)Python爬蟲
- python之正規表示式Python
- python 正規表示式匹配Python
- Python正規表示式手稿Python
- Python正規表示式大全Python
- Python正規表示式匹配字串中的數字Python字串
- python 中的正規表示式學習筆記Python筆記
- java中的正規表示式Java
- JS中的正規表示式JS
- 在 Shell 中轉換 Python 正規表示式Python
- Python正規表示式詳解Python
- Python 正規表示式(RegEx)指南Python
- 詳解 Python 正規表示式Python
- 正規表示式(python3)Python
- re正規表示式庫的簡介、入門、使用方法
- python正規表示式問號的使用Python
- 談談正規表示式中的 “.”
- js中的正規表示式(1)JS
- Grep(Regex)中的正規表示式
- 【正規表示式】常用的正規表示式(數字,漢字,字串,金額等的正規表示式)字串
- Python-day-15-正規表示式Python