在python中使用正则表达式,主要通过下面的几个方法
search(pattern, string, flags=0)
- 扫描整个string并返回匹配pattern的结果(None或对象)
- 有匹配的字符串的话返回一个对象(包含符合匹配条件的第一个字符串),否则返回None
import re
content = 'Hello 1234567 Hello 666'
res = 'Hello\s'
result = re.search(res, content)
if result is not None:
print(result.group())
print(result.span())
res1 = 'Hello\s(\d)(\d+)'
result = re.search(res1, content)
print(result.group(1))
print(result.group(2))
findall(pattern, string, flags=0)
- 扫描整个context并返回匹配res的结果(None或列表)
- 有匹配的字符串的话返回一个列表(符合匹配条件的每个子字符串作为它的一个元素),否则返回None
import re
res = 'Hello\s'
results = re.findall(res, content)
if results is not None:
print(results)
res1 = 'Hello\s(\d)(\d+)'
results = re.findall(res1, content)
if result is not None:
print(results)
sub(pattern, repl, string, count=0, flags=0)
- 可以来修改文本
- 用将用pattern匹配string所得的字符串替换成repl
import re
content = '54aK54yr5oiR54ix5L2g'
res = '\d+'
content = re.sub(res, '', content)
print(content)
compile(pattern, flags=0)
- 将正则表达式res编译成一个正则对象并返回,以便复用
import re
content1 = '2019-12-15 12:00'
content2 = '2019-12-17 12:55'
content3 = '2019-12-22 13:21'
pattern = re.compile('\d{2}:\d{2}')
result1 = re.sub(pattern, '', content1)
result2 = re.sub(pattern, '', content2)
result3 = re.sub(pattern, '', content3)
print(result1, result2, result3)
flags的一些常用值
- re.I 使匹配对大小写不敏感
- re.S 使.匹配包括换行符在内的所有字符
import re
re.compile(res, re.I)
re.compile(res,re.S)
|