python正则表达式 re (二)sub

背景:

re.sub是re模块重要的组成部分,并且功能也非常强大,主要功能实现正则的替换。
re.sub定义:
sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it’s passed the match object and must return
a replacement string to be used.
主要的意思为:对字符串string按照正则表达式pattern,将string的匹配项替换成字符串repl。
公式解析:
pattern为表示正则中的模式字符串,
repl为replacement,被替换的内容,repl可以是字符串,也可以是函数。
string为正则表达式匹配的内容。
count:由于正则表达式匹配到的结果是多个,使用count来限定替换的个数(顺序为从左向右),默认值为0,替换所有的匹配到的结果。
flags是匹配模式,可以使用按位或’|’表示同时生效,也可以在正则表达式字符串中指定。(详情见链接)

举例:

>import re
>re.sub(r'\w+','10',"ji 43 af,geq",2,flags=re.I)
'10 10 af,geq'

详解:首先导入re模块,使用re.sub函数,r’\w+’为正则表达式,匹配英文单词或数字,’10’为被替换的内容,”ji 43 af,geq”为re匹配的字符串内容,count为2 只替换前两个,flags=re.I 忽略大小写。
输出部分自行理解。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值