1.a= 「abbbccc」,用正則匹配為 abccc,不管有多少b,就出現一次?
2.寫出開頭匹配字母和下劃線,末尾是數字的正規表示式?import re
a="abbbccc"
(re.sub(
"b+"
,"b"
,a))
3.匹配乙個手機號import re
res=
"a_0ds23h1234"
(re.findall(
"^[a-za-z_]+.\d$"
,res)
)
4.寫乙個正規表示式,使其能同時識別下面所有的字串:『bat』, 『bit』, 『but』, 『hat』, 『hit』, 'hut『import re
phone=
"15567865678"
(re.findall(
"^1[3456789]\d\d$"
,phone)
)
6.提取每行中完整的年月日和時間字段import re
str1=
"bat, bit, but, hat, hit, hut"
(re.findall(
"..t"
,str1)
)#print(re.findall("[bh][aiu]t",str1))
7.將每行中的電子郵件位址替換為你自己的電子郵件位址import re
s="""se234 1987-02-09 07:30:00
1987-02-10 07:25:00"""
(re.findall(
"\d-\d-\d \d:\d:\d"
,s,re.m)
)
8.匹配\home關鍵字:import re
s="""693152032@qq.com, werksdf@163.com, sdf@sina.com, sfjsdf@139.com, soifsdfj@134.com pwoeir423@123.com"""
(re.sub(
"\w+@\w+[.]com"
,"12345678@qq.com"
,s))
9.匹配一行文字中的所有開頭的數字內容或字母內容import re
str1=
"skjdfoijower \home \homewer"
(re.findall(r"\\home"
,str1)
)
#end:學無止境import re
str1=
"12a321 akda12jnm 32jakjd dka"
(re.findall(r"\b\w"
,str1)
)#只匹配乙個
(re.findall(r"\b\d+|\b[a-za-z]+"
,str1)
)#開頭多個
re 模組簡單運用
import random from random import randint,choice,sample for i in range 20 test random.randint 1,10 1 10之間的整數,包括1和10 test1 random.random 0到1 之間的小數 test2...
re模組的結果小練習題
1.匹配標籤 1 import re2 ret re.search w 3 還可以在分組中利用?p的形式給分組起名字4 獲取的匹配結果可以直接用group 名字 拿到對應的值 5print ret.group 6print ret.group tag name 789 10 ret re.searc...
Python 中re庫的簡單使用
1.findall 方法 返回乙個列表 如下 import re text f open testtext.txt r encoding cp936 for each line in f text text each line f.close result re.findall a z a z a ...