正则表达式(regex): 用来简洁表达一组字符的表达式
通用的字符串框架
简洁表达一组字符串的表达式
针对字符串表达“简洁” 和 “特征” 思想的工具
某字符串的特征归属
在文本中十分常用
字符串匹配
编译:将符合正则表达式语法的字符串转换成正则表达式特征。
Re库为python的标准库。
raw string 类型(原生字符串类型,指不包含转义字符) r'text'
string 类型 if you want to use \, then you have to \\
函数式用法:(6种)
re.search()
re.match()
re.findall()
re.split()
re.finditer()
re.sub()
import re '''return match object''' match = re.search(r'[0-9]\d{5}', 'BIT 100081') if match: match.group(0) print(match.group(0)) '''match will search from the string's beginning''' match = re.match(r'[0-9]\d{5}', 'BIT 100084') if match: print(match.group(0)) '''return list''' match = re.findall(r'[0-9]\d{5}', 'BIT 100083 100085') print(match) '''return list''' match = re.split(r'[0-9]\d{5}', 'BIT 100083 100085', maxsplit=1) print(match) '''return match object''' match = re.finditer(r'[0-9]\d{5}', 'BIT 100083 100085') for ma in match: print(ma.group(0)) '''return replaced string''' match = re.sub(r'[0-9]\d{5}', 'zipcode', 'BIT100083 100085', count=2) print(match)