python进阶(2)——re模块:正则表达式2

re.split 根据模式来分割字符串

import re
text='a, b,,,,c    d'
print(re.split('[, ]+', text))
#re.split:以空格和字符串分割字符

re.findall 返回列表,包含所有与给定模式匹配的子串

import re
pat = '[a-zA-Z]+'
text=' " hmmm ... err --- a  re you sure?" he said,sounding insecure.'
print(re.findall(pat,text))

运行结果

['hmmm', 'err', 'a', 're', 'you', 'sure', 'he', 'said', 'sounding', 'insecure']

re.sub从左往右将与模式匹配的子串替换为指定内容

import re
pat = 'name'
text = 'dear name'
print(re.sub(pat,'Mr.gumby',text))

re.escape用于对字符串中所有可能被视为正则表达式运算符的字符进行转义

包括两种情况:

1 字符串很长,包含大量特殊字符,不想输入大量的反斜杠

2 从用户处(input)获取了一个字符串,想将其用于正则表达式中

import re
print(re.escape('http://www.python.com'))

运行结果:

http\:\/\/www\.python\.com

猜你喜欢

转载自blog.csdn.net/weixin_40725491/article/details/83057609