Python正则表达式re.sub使用

更新时间:2023-06-19 10:16:53 阅读: 评论:0

上汤白菜
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(up(0))
print(up(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

本文发布于:2023-06-19 10:16:53,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/89/1045429.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:字符串   匹配   数字
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图