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

猜你喜欢

转载自www.cnblogs.com/BlueBlueSea/p/10648404.html
今日推荐