python学习——re库的常用函数

04-11 1578阅读

参考资料:python网络爬虫技术与应用【邓维】

python学习——re库的常用函数
(图片来源网络,侵删)

1、match()

        从字符串头部开始匹配字符。

import re
content="The123456ismyonephonenumber."
# 字符串长度
print(len(content)) 
# 使用match匹配,第一个参数为正则表达式,第二个参数为要匹配的字符串
result=re.match(r'^The',content)
print(result)
# 输出匹配内容
print(result.group())
# 输出匹配内容的位置索引
print(result.span())

2、search()

        与match()方法不同,search()方法不需要从头开始匹配。

import re
content="OtherThe123456ismyonephonenumber."
result=re.search(r"The.*?(\d+).*?number.",content)
print(result.group())

3、findall()

        match()方法和search()方法都是返回匹配到的第一个内容就结束匹配,而findall()方法是返回全部符合匹配规则的内容,返回的是一个列表。

import re
text="pyypppyyyyypppp"
pattern="py"
for match in re.findall(pattern,text):
    print("Found{!r}".format(match))

4、sub()

        去除或替换匹配的字符。假如写sub("\d+","-"),则是把匹配的内容调换成“-”,例子如下:

import re
content='54abc59de335f7778888g'
content=re.sub("\d+","",content)
print(content)
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]