python爬虫数据解析之正则表达式及re.match()匹配单个字符方法

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值