这篇文章给大家介绍怎么在python中利用re.match()对多个字符进行匹配,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
import re
text = "123h2ello 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())
输出结果为
123
123Process finished with exit code 0
示例2:*
需求:匹配出,一个字符串第一个字母为大小字符,后面都是小写字母并且这些小写字母可有可无
import re
#注意是前一个字符
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())
#运行结果
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)
输出结果为
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)
#运行结果
变量名 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())
输出结果为
h
HProcess finished with exit code 0
示例2:?
需求:匹配出0到99之间的数字
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())
#运行结果
7
33
0 # 这个结果并不是想要的,利用$才能解决
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())
输出结果为
he
Hel
hellProcess finished with exit code 0
示例2:{m}
需求:匹配出,8到20位的密码,可以是大小写英文字母、数字、下划线
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())
#运行结果
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
关于怎么在python中利用re.match()对多个字符进行匹配就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。