str.split()与re.split()的区别

时间:2023-03-09 09:09:32
str.split()与re.split()的区别

str.split():

>>>'hello, world'.split()
>>>['hello,','world']
>>>'hello, world'.split(',')
>>>['hello',' world']

re.split():

re.split()方法可以使用正则表达式匹配,具体用法如下

re.split(r'\W+','hello, world')
['hello','world']

如果使用带括号的正则表达式则可以将正则表达式匹配的内容也添加到列表内,例如

>>>re.split(r'(\W+)','hello, world')
>>>['hello',', ','world']

使用实例:

>>> url = "https://www.zhihu.com/question/34963917/answer/139938429"
>>> re.split("(https?://[\w.:]*)",url)
['', 'https://www.zhihu.com', '/question/34963917/answer/139938429']