re.S (使 . 匹配包括换行在内的所有字符)
re.I(不区分大小写)
re.M(多行匹配)
^
只匹配字符串的开头,$
只匹配字符串结尾,.
不匹配换行符.
re.S做的事情是: 让.
也匹配换行符
re.M做的事情是: 让^
匹配每行的开头,$
匹配每行的结尾
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
text = """First line.
Second line.
Third line."""
pattern = "^(.*?)$" # Match anything from the start to end. 非贪婪匹配
# 让^、$只匹配字符串的开头、结尾, .不匹配换行符
ret1 = re.search(pattern, text)
print("ret1----%s", ret1)
# 让.匹配换行符
ret2 = re.search(pattern, text, re.S)
print("ret2---%s",ret2.group())
# 让^、$匹配每行的开头、结尾, 同时让.匹配换行符, 且pattern是非贪婪匹配
ret3 = re.search(pattern, text, re.M | re.S)
print("ret3----%s",ret3.group())
# 让^、$匹配每行的开头、结尾, 同时让.匹配换行符, 且pattern是贪婪匹配
ret4 = re.search("^(.*)$", text, re.M | re.S)
print("ret4----%s", ret4.group())
# 让^、$匹配每行的开头、结尾, 非贪婪
ret5 = re.findall(pattern, text, re.M)
print("ret5----%s", ret5)
运行结果:
原文地址:https://www.jianshu.com/p/fe7441d9cc7b,如有侵权,请联系删除