python下re模块的常用方法

1.re.search(a,b)用于在字符串b中匹配正则表达式a

#分组提取字符串
text = "apple 's price is $299, orange 's price is $199"

res = re.search(".*(\$\d+).*(\$\d+)", text)

print(res.groups())

输出结果为
(’$299’, ‘$199’)

2.re.findall(a,b)用于在字符串b中匹配正则表达式a,以列表形式返回全部符合规则的字符串

#匹配全部符合规则的字串

text = "apple 's price is $299, orange 's price is $199"

res1 = re.findall("\$\d+", text)

print(res1)

输出结果为
[’$299’, ‘$199’]

3.re.sub(a,b,c,d) a被替换字串或正则表达式,b为替换串,c为模式串,d表示替换几个符合规则的被替换字串,默认为全部替换

text = "apple 's price is $299, orange 's price is $199"

res2 = re.sub("\$\d+", "$100", text)

print(res2)

输出结果为
apple 's price is $100, orange 's price is $100

4.re.split(a,b)用于分割字符串,a为分隔符正则表表达式,b为被分割串,以列表形式返回

text = "hello$world ni hao"

res1 = re.split("[$ ]", text)

print(res1)

输出结果为
[‘hello’, ‘world’, ‘ni’, ‘hao’]

5.re.compile()用于提前编译常用正则表达式以加快运行效率,且可多行编写正则表达式,便于书写注释,示例如下

#提前编译常用正则表达式 并且加以注释
text = "the number is 20.50"
r = re.compile(r"""
                \d+  #小数点前的整数 + 表示至少一个字符
                .?  #小数点本身   ?表示小数点可有可无,匹配0或一个字符
                \d*  #小数点后的小数部分  *表示匹配0或多个字符 即小数部分可有可无
                """, re.VERBOSE)
res2 = re.search(r, text)
print(res2.group())

输出结果为
20.50

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值