re.match(a,b)方法匹配字符串b是否以a开头,是的话返回a,否则返回None
1.匹配某字符串a是否以字符h开头
import re
text = "hello world"
res = re.match("h", text)
print(res.group())
输出结果为
h
Process finished with exit code 0
2. .匹配除换行符外的任意字符
import re
text = "+hello world"
text1 = "\nhello world"
res = re.match(".", text)
res1 = re.match(".", text1)
print(res.group())
print(res1.group())
输出结果为
+
None
Process finished with exit code 0
3. \d 匹配任意数字字符(0-9)
import re
text = "9hello world"
text1 = "5hello world"
text3 = "hello world"
res = re.match("\d", text)
res1 = re.match("\d", text1)
res2 = re.match("\d", text3)
print(res.group())
print(res1.group())
print(res2.group())
输出结果为
9
5
None
Process finished with exit code 0
4. \D匹配任意的非数字字符
import re
text = "+hello world"
text1 = "5hello world"
res = re.match("\D", text)
res1 = re.match("\D", text1)
print(res.group())
print(res1)
输出结果为
+
None
Process finished with exit code 0
5. \s匹配任意的空白字符 包括(1.\n 2.\r 3.\t 4.空格)注:\r在windows下用于换行符
import re
text = "\tello world"
text1 = "hello world"
res = re.match("\s", text)
res1 = re.match("\s", text1)
print(res.group())
print(res1)
输出结果为
None
Process finished with exit code 0
6. \w匹配 包括a-z,A-Z,数字或下划线的任意字符
import re
text = "hello world"
text1 = "Hello world"
text2 = "1hello world"
text3 = "_hello world"
text4 = "+Hello world"
res = re.match("\w", text)
res1 = re.match("\w", text1)
res2 = re.match("\w", text2)
res3 = re.match("\w", text3)
res4 = re.match("\w", text4)
print(res.group())
print(res1.group())
print(res2.group())
print(res3.group())
print(res4)
输出结果为
h
H
1
_
None
Process finished with exit code 0
7. \W 匹配除a-z,A-Z,数字,下划线以外的任意字符(不作示例)
8. []组合的方式 只要满足[]中的字符即可匹配
import re
text = "hello world"
text1 = "1Hello world"
text2 = "+hello world"
res = re.match("[h1]", text)
res1 = re.match("[h1]", text1)
res2 = re.match("[h1]", text2)
print(res.group())
print(res1.group())
print(res2)
输出结果为
h
1
None
Process finished with exit code