re库
常用方法
search()
在字符串中查找符合正则表达式的,返回第一位置的结果;结果为match对象
1 | re.search(pattern, String, flags=0) |
1 | # flag常用标记 |
1 | match = re.search(r'[1-9]/d{5}', 'BIT 234567') |
match()
从字符串开始位置匹配正则表达式,匹配则返回match对象
1 | re.match(pattern, String, flags=0) |
1 | match=re.match(r'[1-9]/d{5}', 'BIT 100085') |
findall()
1 | re.findall(pattern, string, flag=0) |
1 | LS = re.findall('[1-9]/d{5}', 'BIT 12345 BIT 23567') |
find()
返回所有匹配结果,以列表形式返回
split()
以正则表达式分割字符串,返回列表
1 | re.split(pattern, string, maxsplit=0, flags=0) |
finditer()
搜索字符串,返回一个匹配结果的迭代类型;match对象
1 | from m in re.finditer(r'[1-9]/d{5}, 'BIT100081 TSU100084'): |
sub()
替换所有匹配结果的字符串,返回替换后字符串
1 | re.sub(pattern, repl, string, count=0, flags=0) |
面向对象的方法
1 | regex = re.compile(pattern, flag=0) |
match对象
match对象的属性
- String 待匹配的字符串
- re 匹配时使用的pattern对象
- pos 正则表达式搜索文本的开始位置
- endpos 正则表达式搜索文本的结束位置
match对象的方法
- group() 返回匹配的字符串
- start() 匹配字符串的开始位置
- end() 匹配字符串的结束位置
- span() 返回(start(), end())