正則表達式【範圍性匹配】
阿新 • • 發佈:2017-10-18
bsp com pre www. find compile 轉義 什麽 sna
1、
import re key = r"<html><body><h1>hello world<h1></body></html>"#這段是你要匹配的文本 p1 = r"(?<=<h1>).+?(?=<h1>)"#這是我們寫的正則表達式規則,你現在可以不理解啥意思 pattern1 = re.compile(p1)#我們在編譯這段正則表達式 matcher1 = re.search(pattern1,key)#在源文本中搜索符合正則表達式的部分 print(matcher1.group(0))#打印出來 #hello world
2、
import re key = r"javapythonhtmlvhdl"#這是源文本 p1 = r"python"#這是我們寫的正則表達式 pattern1 = re.compile(p1)#同樣是編譯 matcher1 = re.search(pattern1,key)#同樣是查詢 print(matcher1.group(0)) #python
3、
import re key = r"<h1>hello world<h1>"#源文本 p1 = r"<h1>.+<h1>"#我們寫的正則表達式,下面會將為什麽【.字符在正則表達式代表著可以代表任何一個字符(包括它本身)】 pattern1 = re.compile(p1) print(pattern1.findall(key))#發沒發現,我怎麽寫成findall了?咋變了呢? #[‘<h1>hello world<h1>‘]
4、#正則表達式中有一個字符\,這個符號通常用來把特殊的符號轉成普通的,把普通的轉成特殊的,
#我們在.的前面加上了轉義符\,但是並不是代表匹配“\.”的意思,而是只匹配“.”的意思
import re key = r"[email protected]" p1 = r"[email protected]\.edu\.cn" pattern1 = re.compile(p1) print (pattern1.findall(key)) #[‘[email protected]‘]
5、#有沒有發現我們第一次用.時,後面還跟了一個+?那這個加號是幹什麽的呢
#“.字符在正則表達式代表著可以代表任何一個字符(包括它本身)”,但是"hello world"可不是一個字符。
# +的作用是將前面一個字符或一個子表達式重復一遍或者多遍
#比方說表達式“ab+”那麽它能匹配到“abbbbb”,但是不能匹配到"a",它要求你必須得有個b,多了不限,少了不行
#問我有沒有那種“有沒有都行,有多少都行的表達方式”,回答是有的。【*】跟在其他符號後面表達可以匹配到它0次或多次
比方說我們在王葉內遇到了鏈接,可能既有http://開頭的,又有https://開頭的,我們怎麽處理?
import re key = r"http://www.nsfbuhwe.com and https://www.auhfisna.com"#胡編亂造的網址,別在意 p1 = r"https*://"#看那個星號! pattern1 = re.compile(p1) print (pattern1.findall(key)) #[‘http://‘, ‘https://‘]
6、[]
代表匹配裏面的字符中的任意一個
import re key = r"lalala<hTml>hello</Html>heiheihei" p1 = r"<[Hh][Tt][Mm][Ll]>.+?</[Hh][Tt][Mm][Ll]>" pattern1 = re.compile(p1) print pattern1.findall(key) #[‘<hTml>hello</Html>‘]
正則表達式【範圍性匹配】