正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。re 模块使 Python 语言拥有全部的正则表达式功能。
import re
#re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
#re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。
print(re.match('www', 'www.runoob.com').span())
#不在起始位置匹配
print(re.match('com', 'www.runoob.com'))
line = 'Cat are smarter than dogs'
matchObj = re.match(r'(.*) are (.*?) (.*)', line, re.M|re.I)
if matchObj:
print("matchObj.group() : ", matchObj.group())
print("matchObj.group(1) : ", matchObj.group(1))
print("matchObj.group(2) : ", matchObj.group(2))
print("matchObj.group(3) : ", matchObj.group(3))
else:
print("No match!!")
#re.search 扫描整个字符串并返回第一个成功的匹配。
print(re.search('www', 'www.runoob.com').span())
#不在起始位置匹配
print(re.search('com', 'www.runoob.com').span())
#re.sub用于替换字符串中的匹配项
phone = "2004-959-559 # 这是一个电话号码"
#删除注释
num = re.sub(r'#.*$', '', phone)
print('电话号码:', num)
#移除非数字的内容
num = re.sub(r'\D', '', phone)
print('电话号码:', num)
运行结果:
D:\python3.6.1\python.exe
F:/python_Advanced/pattern.py
(0, 3)
None
matchObj.group() : Cat are smarter than dogs
matchObj.group(1) : Cat
matchObj.group(2) : smarter
matchObj.group(3) : than dogs
(0, 3)
(11, 14)
电话号码: 2004-959-559
电话号码: 2004959559
Process finished with exit code 0