我是靠谱客的博主 唠叨电源,这篇文章主要介绍python爬虫数据解析之正则表达式及re.match()匹配单个字符方法re.match(a,b)方法匹配字符串b是否以a开头,是的话返回a,否则返回None1.匹配某字符串a是否以字符h开头2.   .匹配除换行符外的任意字符3.  \d 匹配任意数字字符(0-9)4.   \D匹配任意的非数字字符5.   \s匹配任意的空白字符  包括(1.\n  2.\r  3.\t   4.空格)注:\r在windows下用于换行符6.  \w匹配  包括a-z,A-Z,数字或下划线的任意字符7. \,现在分享给大家,希望可以做个参考。

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

最后

以上就是唠叨电源最近收集整理的关于python爬虫数据解析之正则表达式及re.match()匹配单个字符方法re.match(a,b)方法匹配字符串b是否以a开头,是的话返回a,否则返回None1.匹配某字符串a是否以字符h开头2.   .匹配除换行符外的任意字符3.  \d 匹配任意数字字符(0-9)4.   \D匹配任意的非数字字符5.   \s匹配任意的空白字符  包括(1.\n  2.\r  3.\t   4.空格)注:\r在windows下用于换行符6.  \w匹配  包括a-z,A-Z,数字或下划线的任意字符7. \的全部内容,更多相关python爬虫数据解析之正则表达式及re.match()匹配单个字符方法re.match(a,b)方法匹配字符串b是否以a开头,是的话返回a,否则返回None1.匹配某字符串a是否以字符h开头2. 内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(61)

评论列表共有 0 条评论

立即
投稿
返回
顶部