Python正则表达式re.sub使用

1、引入正则表达式

import re

2、使用re.sub进行字符串替换

re.sub(pattern, repl, string, count=0, flags=0) 
         其中三个必选参数:pattern, repl, string
         两个可选参数:count, flags
  1. pattern ,表示正则中的模式字符串,其中反斜杠加数字(\N),则对应着匹配的组(matched group)
    比如\6,表示匹配前面pattern中的第6个group,意味着,pattern中,前面肯定是存在对应的,第6个group,然后你后面也才能去引用;
  2. repl, 就是replacement,被替换,的字符串的意思。repl可以是字符串,也可以是函数;
  3. string ,即表示要被处理,要被替换的那个string字符串;
  4. count ,表示匹配pattern中被处理的匹配字符串个数;

练习1

import re
inputStr = "hello crifan, nihao crifan, nihao ccc "
match_str=re.match(r"hello (\w+)",inputStr)  #\w匹配字母、数字、下划线
print(match_str.group(0))
print(match_str.group(1))
replacedStr = re.sub(r"hello (\w+), nihao \1", "crifanli", inputStr)
print(replacedStr)

运行结果:

hello crifan
crifan
hello crifan, nihao crifan, nihao ccc

练习2:提取输入字符串中的数字

import re
option=input("")
option_str=re.sub("\D","",option)  #\D匹配非数字字符
print(option_str)

运行结果:

生活1生活2
12

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chde2Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值