【代码示例】re模块方法使用。
>>> import re
>>> text="172.0.0.1"
>>> print(re.split("[\.]+",text))#按照模式进行字符串分割,此处按照“.”进行分割
['172', '0', '0', '1']
['today', 'is', 'sunday']
>>> import re
>>> text="today is sunday"
>>> print(re.findall("[a-zA-Z]+",text))#找出字符串中所有单词。
['today', 'is', 'sunday']
>>> import re
>>> text="Mr Wu is a handsome boy, he is cool, clever, and soon..."
>>> print(re.sub("\s+","-",text))#用“-”替换字符串中所有的空白
Mr-Wu-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on...
>>> import re
>>> text="ok or not ok, that is a question!"
>>>print(re.match("\w",text))#从头开始匹配,匹配一个字符是否为字母。如果 #匹配不成功,则返回None
<_sre.SRE_Match object; span=(0, 1), match='o'>
>>> import re
>>> text="Ok or not ok, that is a question!"
>>>print(re.search("ok",text))#从整个字符串去匹配,成功则返回macth对象,否#则为None
<_sre.SRE_Match object; span=(10, 12), match='ok'>
search方法需要区别于match方法,请仔细查看下列例子,返回的则为None。
>>> import re
>>> text="Ok or not ok, that is a question!"
>>> print(re.match("ok",text))#该方法从开始进行匹配,不是从字符串全部去匹配。
None
>>> import re
>>> text="https://www.baidu.com/*?()"
>>> print(re.escape(text))#对字符串中所有特殊正则表达式字符进行转义。
https\:\/\/www\.baidu\.com\/\*\?\(\) #转义后的字符串