import re text = "123h1ello world" text1 = "123Hello world456" text2 = "hello world" res = re.match("\d*", text) res1 = re.match("\d*", text1) res2 = re.match("\d*", text2) print(res.group()) print(res1.group()) print(res2.group())
輸出結(jié)果為
123
123Process finished with exit code 0
示例2:*
需求:匹配出,一個(gè)字符串第一個(gè)字母為大小字符,后面都是小寫字母并且這些小寫字母可有可無(wú)
import re #注意是前一個(gè)字符 ret = re.match("[A-Z][a-z]*","M") print(ret.group()) ret = re.match("[A-Z][a-z]*","AaBcDE") print(ret.group()) ret = re.match("[A-Z][a-z]*","Aabcdef") print(ret.group())
#運(yùn)行結(jié)果
M
Aa
Aabcdef
import re text = "he+llo world" text1 = "Hello world456" text2 = "+hello world" res = re.match("\w+", text) res1 = re.match("\w+", text1) res2 = re.match("\w+", text2) print(res.group()) print(res1.group()) print(res2)
輸出結(jié)果為
he
Hello
NoneProcess finished with exit code 0
示例2:+
需求:匹配出,變量名是否有效
import re names = ["name1","_name","2_name","__name__"] for i in names: ret = re.match("[a-zA-Z_]+[\w]*",i) if ret: print("變量名 %s 符合要求" % ret.group()) else: print("變量名 %s 非法" % i)
#運(yùn)行結(jié)果
變量名 name1 符合要求
變量名 _name 符合要求
變量名 2_name 非法
變量名 __name__ 符合要求
import re text = "he+llo world" text1 = "Hello world456" text2 = "+hello world" res = re.match("\w?", text) res1 = re.match("\w?", text1) res2 = re.match("\w?", text2) print(res.group()) print(res1.group()) print(res2.group())
輸出結(jié)果為
h
HProcess finished with exit code 0
示例2:?
需求:匹配出0到99之間的數(shù)字
import re ret = re.match("[1-9]?[0-9]","7") print(ret.group()) ret = re.match("[1-9]?\d","33") print(ret.group()) ret = re.match("[1-9]?\d","09") print(ret.group())
#運(yùn)行結(jié)果
7
33
0 # 這個(gè)結(jié)果并不是想要的,利用$才能解決
import re text = "he+llo world" text1 = "Hello world456" text2 = "hello world" res = re.match("\w{2}", text) res1 = re.match("\w{3}", text1) res2 = re.match("\w{4}", text2) print(res.group()) print(res1.group()) print(res2.group())
輸出結(jié)果為
he
Hel
hellProcess finished with exit code 0
示例2:{m}
需求:匹配出,8到20位的密碼,可以是大小寫英文字母、數(shù)字、下劃線
import re ret = re.match("[a-zA-Z0-9_]{6}","123a3g45678") print(ret.group()) ret = re.match("[[a-zA-Z0-9_]{8,20}","1ad3123456addfcasdef") print(ret.group())
#運(yùn)行結(jié)果
123a3g
1ad3123456addfcasdef
import re text = "hello world" text1 = "Helloworld456" text2 = "hello world" res = re.match("\w{2,5}", text) res1 = re.match("\w{6,8}", text1) res2 = re.match("\w{20,25}", text2) print(res.group()) print(res1.group()) print(res2)
hello
Hellowor
NoneProcess finished with exit code 0
到此這篇關(guān)于python正則表達(dá)式re.match()匹配多個(gè)字符方法的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)python re.match()匹配字符內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:廊坊 重慶 東莞 長(zhǎng)春 漢中 臨汾 河池 德宏
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python正則表達(dá)式re.match()匹配多個(gè)字符方法的實(shí)現(xiàn)》,本文關(guān)鍵詞 python,正則,表達(dá)式,re.match,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。