Python中如何使用正则表达式进行字符串匹配?
- 内容介绍
- 文章标签
- 相关推荐
本文共计205个文字,预计阅读时间需要1分钟。
验证字符串是否是网站地址:
pythonimport re
text1='www.12.com'text2='http://www.runoob.com:80//-tutorial.'strinfo1=re.compile(r'www.\w+.com')strinfo2=re.compile(r'www.\w+\.com')
result1=bool(strinfo1.match(text1))result2=bool(strinfo2.match(text2))
print(text1 is a website:, result1)print(text2 is a website:, result2)
验证字符串是否是网站
import retext1 ='www.12.com'
text2='www.runoob.com:80/html/html-tutorial.html'
strinfo1=re.compile(r'www.\w+.com')
strinfo2=re.compile(r'www.(\w+).com') #加()小括号,表示子表达式,匹配结果为子表达式里的内容
strinfo3=re.compile(r'(\w+)://')
res1=strinfo1.findall(text1)
res2=strinfo2.findall(text1)
res3 = strinfo3.match(text2) #match返回结果为一个对象,获得匹配结果需要结合group()
print (res1) #findall匹配返回结果为列表
print (res2)
print (res3.group()) #group()匹配返回结果为字符串
本文共计205个文字,预计阅读时间需要1分钟。
验证字符串是否是网站地址:
pythonimport re
text1='www.12.com'text2='http://www.runoob.com:80//-tutorial.'strinfo1=re.compile(r'www.\w+.com')strinfo2=re.compile(r'www.\w+\.com')
result1=bool(strinfo1.match(text1))result2=bool(strinfo2.match(text2))
print(text1 is a website:, result1)print(text2 is a website:, result2)
验证字符串是否是网站
import retext1 ='www.12.com'
text2='www.runoob.com:80/html/html-tutorial.html'
strinfo1=re.compile(r'www.\w+.com')
strinfo2=re.compile(r'www.(\w+).com') #加()小括号,表示子表达式,匹配结果为子表达式里的内容
strinfo3=re.compile(r'(\w+)://')
res1=strinfo1.findall(text1)
res2=strinfo2.findall(text1)
res3 = strinfo3.match(text2) #match返回结果为一个对象,获得匹配结果需要结合group()
print (res1) #findall匹配返回结果为列表
print (res2)
print (res3.group()) #group()匹配返回结果为字符串

