python正则表达式re.match()匹配多个字符⽅法的实现1.  *表⽰匹配任意多个字符  \d*表⽰匹配任意多个数字字符
import re
text = "123h1ello world"
text1 = "123Hello world456"
text2 = "hello world"
res = re.match("\d*", text)
正则化匹配26个字母pythonres1 = re.match("\d*", text1)
res2 = re.match("\d*", text2)
up())
up())
up())
输出结果为
123
123
Process finished with exit code 0
⽰例2:*
需求:匹配出,⼀个字符串第⼀个字母为⼤⼩字符,后⾯都是⼩写字母并且这些⼩写字母可有可⽆
import re
#注意是前⼀个字符
ret = re.match("[A-Z][a-z]*","M")
up())
ret = re.match("[A-Z][a-z]*","AaBcDE")
up())
ret = re.match("[A-Z][a-z]*","Aabcdef")
up())
#运⾏结果
M
Aa
Aabcdef
2.  +表⽰匹配1个或者多个任意字符  \w+表⽰匹配⼀个或多个字母,数字或下划线
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)
up())
up())
print(res2)
输出结果为
he
Hello
None
Process 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 符合要求" % up())
else:
print("变量名 %s ⾮法" % i)
#运⾏结果
变量名 name1 符合要求
变量名 _name 符合要求
变量名 2_name ⾮法
变量名 __name__ 符合要求
3.  ?表⽰匹配0个或⼀个字符    \w?表⽰匹配0或1个字母,数字或下划线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)
up())
up())
up())
输出结果为
h
H
Process finished with exit code 0
⽰例2:?
需求:匹配出0到99之间的数字
import re
ret = re.match("[1-9]?[0-9]","7")
up())
ret = re.match("[1-9]?\d","33")
up())
ret = re.match("[1-9]?\d","09")
up())
#运⾏结果
7
33
0 # 这个结果并不是想要的,利⽤$才能解决
4.  {m}表⽰匹配m个字符    \d{11}表⽰匹配11个数字字符
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)
up())
up())
up())
输出结果为
he
Hel
hell
Process finished with exit code 0
⽰例2:{m}
需求:匹配出,8到20位的密码,可以是⼤⼩写英⽂字母、数字、下划线
import re
ret = re.match("[a-zA-Z0-9_]{6}","123a3g45678")
up())
ret = re.match("[[a-zA-Z0-9_]{8,20}","1ad3123456addfcasdef")
up())
#运⾏结果
123a3g
1ad3123456addfcasdef
5.  {m,n}表⽰匹配m-n个字符  \w{2,4}表⽰匹配2-4个字符
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)
up())
up())
print(res2)
hello
Hellowor
None
Process finished with exit code 0
到此这篇关于python正则表达式re.match()匹配多个字符⽅法的实现的⽂章就介绍到这了,更多相关python re.match()匹配字符内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。