Django30——re.findall使用
在
re.py中定义如下:
def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string.
If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result."""
return _compile(pattern, flags).findall(string)
返回string中所有与pattern匹配的全部字符串,返回形式为数组。
1、常用正则表达式
import re str = aabbabaabbaa # .是匹配除 (换行符)以外的任意一个字符 print(re.findall(ra.b,str)) #[aab, aab] # *前面的字符出现0次或以上 print(re.findall(ra*b,str)) #[aab, b, ab, aab, b] # .* 贪婪,匹配从.*前面为开始到后面为结束的所有内容 print(re.findall(ra.*b,str)) #[aabbabaabb] # .*? 非贪婪,遇到开始和结束就进行截取,因此截取多次符合的结果,中间没有字符也会被截取 print(re.findall(ra.*?b,str)) #[aab, ab, aab] # (.*?) 非贪婪,与上面一样,只是与上面的相比多了一个括号,只保留括号的内容 print(re.findall(ra(.*?)b,str)) #[a, , a]
2、re.S
import re
str =
aabbab
aabbaa
bb
# 参数无re.S,没有把最后一个换行的aab算进来
print(re.findall(ra.*?b,str)) #[aab, ab, aab]
# 参数有re.S,不会对
进行中断
print(re.findall(ra.*?b,str,re.S)) #[aab, ab, aab, aa
b]
