Py中re.sub学习【转载】

转自:https://www.crifan.com/python_re_sub_detailed_introduction/

//这个网址讲的不错。

1.re.sub的功能

re是regular expression的缩写,表示正则表达式

sub是substitute的缩写,表示替换;

re.sub是个正则表达式方面的函数,用来实现通过正则表达式,实现比普通字符串的replace更加强大的替换功能;

inputStr = "hello 111 world 111"
replacedStr = inputStr.replace("111", "222")
//这样可以进行替换

 

inputStr = "hello 123 world 456"
replacedStr = re.sub("\d+", "222", inputStr)
//这样可以把数字都换为222

 

 对于输入的一个字符串,利用正则表达式(的强大的字符串处理功能),去实现(相对复杂的)字符串替换处理,然后返回被替换后的字符串.

2.re.sub的各个参数的详细解释

re.sub共有五个参数。

其中三个必选参数:patternreplstring

两个可选参数:countflags

 

2020-3-9————————————————

看自己以前写的博客,真是辣鸡。。。学的真是太不认真了。

1.小例子

import re
text="a\ncfoda!!"
text=re.sub(r"[^a-zA-Z0-9]"," ",text)
print(text)

#输出:
a cfoda  

 

可以发现,它会将换行符\n去掉,而且标点符号英文/中文都去掉了。

2.总体学习

https://github.com/ziishaned/learn-regex/blob/master/translations/README-cn.md

可以发现这个讲的非常详细!善用知乎。。。

https://www.runoob.com/python/python-reg-expressions.html

这个也讲的很全面。

 

 

import re
text="The car parked in the garage."
text=re.findall(r".ar",text)
print(text)

#输出:
['car', 'par', 'gar']

 

是找到所有的。

import re
text="The car parked in the garage."
text=re.sub(r".ar","233",text)
print(text)

#输出:
The 233 233ked in the 233age.

 

sub是替换,学会了正则语法的规则和这两个函数基本就可了。

但是有一点奇怪,\是不用在{}前吗?。。。

import re
text="The {car} parked in the garage."
text=re.sub(r"\{\}","233",text)
print(text)
#输出:
The {car} parked in the garage.


text=re.sub(r"{","233",text)
#输出:
The 233car} parked in the garage.
#这个倒是可以匹配上的

 

posted @ 2019-04-03 14:01  lypbendlf  阅读(207)  评论(0编辑  收藏  举报