失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Python正则表达式re.sub使用

Python正则表达式re.sub使用

时间:2019-02-01 19:38:32

相关推荐

Python正则表达式re.sub使用

1、引入正则表达式

import re

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

re.sub(pattern, repl, string, count=0, flags=0) 其中三个必选参数:pattern, repl, string两个可选参数:count, flags

pattern,表示正则中的模式字符串,其中反斜杠加数字(\N),则对应着匹配的组(matched group)

比如\6,表示匹配前面pattern中的第6个group,意味着,pattern中,前面肯定是存在对应的,第6个group,然后你后面也才能去引用;repl, 就是replacement,被替换,的字符串的意思。repl可以是字符串,也可以是函数;string,即表示要被处理,要被替换的那个string字符串;count,表示匹配pattern中被处理的匹配字符串个数;

练习1

import reinputStr = "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 reoption=input("")option_str=re.sub("\D","",option) #\D匹配非数字字符print(option_str)

运行结果:

生活1生活2

12

如果觉得《Python正则表达式re.sub使用》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。