python模块re库的全部用法_re库的用法介绍

re库是python的标准库

re库采用raw string类型表示正则表达式,表示为:r'test'

原生字符串(raw string)是不包含转义符的字符串

例子:

爬取好房通的网站优优好房的房源时用到了re库解析文本,

raw string:

r'[1-9]\d{5}'

r'\d{3}-\d{8}|\d{4}-\d{7}'

string:

'[1-9]\\d{5}'

'\\d{3}-\\d{8}|\\d{4}-\\d{7}'

Re库主要功能函数

0053af01554e

re.search(pattern, string, flags=0)

pattern:正则表达式的字符串或原生字符串表示

string:待匹配字符串

flags:正则表达式使用时的控制标记

0053af01554e

0053af01554e

re.match(pattern,string,flags=0)

因为match为从开始位置开始匹配,使用时要加if进行判别返回结果是否为空,否则会报错

0053af01554e

re.findall(pattern,string,flags=0)

0053af01554e

re.split(pattern,string,maxsplit=0,flags=0)

maxsplit为最大分割数,剩余部分作为最后一个元素输出

0053af01554e

re.finditer(pattern,string,flags=0)

0053af01554e

re.sub(pattern,repl,string,count=0,flags=0)

repl是用来替换的字符串,count为替换次数

0053af01554e

Re库的另一种等价用法

Re库的函数式用法为一次性操作,还有一种为面向对象用法,可在编译后多次操作

1regex = re.compile(pattern,flags=0)

通过compile生成的regex对象才能被叫做正则表达式

0053af01554e

Re库的match对象

Match对象的属性

0053af01554e

Match对象的方法

0053af01554e

实例

0053af01554e

Re库的贪婪匹配和最小匹配

Re库默认采取贪婪匹配,即输出匹配最长的子串

0053af01554e

re库是python的标准库

re库采用raw string类型表示正则表达式,表示为:r'test'

原生字符串(raw string)是不包含转义符的字符串

例子:

爬取好房通的网站优优好房的房源时用到了re库解析文本,

raw string:

r'[1-9]\d{5}'

r'\d{3}-\d{8}|\d{4}-\d{7}'

string:

'[1-9]\\d{5}'

'\\d{3}-\\d{8}|\\d{4}-\\d{7}'

Re库主要功能函数

0053af01554e

re.search(pattern, string, flags=0)

pattern:正则表达式的字符串或原生字符串表示

string:待匹配字符串

flags:正则表达式使用时的控制标记

0053af01554e

0053af01554e

re.match(pattern,string,flags=0)

因为match为从开始位置开始匹配,使用时要加if进行判别返回结果是否为空,否则会报错

0053af01554e

re.findall(pattern,string,flags=0)

0053af01554e

re.split(pattern,string,maxsplit=0,flags=0)

maxsplit为最大分割数,剩余部分作为最后一个元素输出

0053af01554e

re.finditer(pattern,string,flags=0)

0053af01554e

re.sub(pattern,repl,string,count=0,flags=0)

repl是用来替换的字符串,count为替换次数

0053af01554e

Re库的另一种等价用法

Re库的函数式用法为一次性操作,还有一种为面向对象用法,可在编译后多次操作

1regex = re.compile(pattern,flags=0)

通过compile生成的regex对象才能被叫做正则表达式

0053af01554e

Re库的match对象

Match对象的属性

0053af01554e

Match对象的方法

0053af01554e

实例

0053af01554e

Re库的贪婪匹配和最小匹配

Re库默认采取贪婪匹配,即输出匹配最长的子串

0053af01554e

0053af01554e

0053af01554e

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值