re 模块提供了 3 个方法对输入的字符串进行确切的查询, match 和 search 最多只会返回一个匹配条件的子串, 可以理解为非贪婪模式, 而 findall 会返回 N 个匹配条件的子串, 可以理解为贪婪模式
- re.match()
- re.search()
- re.findall()
- #match() 方法的工作方式是只有当被搜索字符串的开头匹配模式的时候它才能查找到匹配对象, match 返回的是对象, 对象里面包含了很多信息
- match=re.match(rdog,dog cat dog) #只要匹配到满足条件的就不匹配了
- print match.group(0) #dog
- print match.start() #0
- print match.end() #3
- match=re.match(rcat,dog cat dog)
- print type(match) #<type NoneType> #因为 cat 没有在字符串的开头, 所以没有匹配到
- #search() 方法和 match() 类似, 不过 search() 方法不会限制我们只从字符串的开头查找匹配, 它匹配子串, 直到匹配到为止或者字符串结束为止
- match=re.search(rcat,dog cat dog)
- print match.group(0) #cat, 如果不分组, 默认就是第 0 组
- print match.start() #4
- print match.end() #7
- #findall 返回的是列表
- match=re.findall(rdog, dog cat dog) #匹配是整个字符串, 每个子串都要匹配, 匹配到的字符串剔除, 后面的字符串要继续匹配正则条件, 直到字符串的结尾, 有多少匹配多少
- print match #[dog, dog]
- # 使用 mathch.group 分组使用 (), 分组和不分组匹配的 "大子串" 都是一样, 但是分组之后, 可以对这些子组做单独处理
- contactInfo = Doe, John: 555-1212
- match=re.search(r\w+, \w+: \S+, contactInfo)
- print match.group(0) #Doe, John: 555-1212
- match = re.search(r(\w+), (\w+): (\S+), contactInfo)
- print match.group(0) #Doe, John: 555-1212, 第 0 组表示匹配的 "大子串", 满足全部条件
- print match.group(1) #Doe
- print match.group(2) #John
- print match.group(3) #555-1212
- # 当一个正则表达式有很多分组的时候, 通过组的出现次序来定位就会变的不现实 Python 还允许你通过下面的语句来指定一个组名:
- match = re.search(r(?P<last>\w+), (?P<first>\w+): (?P<phone>\S+), contactInfo)
- print match.group(last) #Doe
- print match.group(first) #John
- print match.group(phone) #555-1212
- # 尽管 findall() 方法不返回分组对象, 它也可以使用分组类似的, findall() 方法将返回一个元组的集合, 其中每个元组中的第 N 个元素对应了正则表达式中的第 N 个分组
- match=re.findall(r\w+, \w+: \S+, contactInfo)
- print match #[Doe, John: 555-1212]
- match=re.findall(r(\w+), (\w+): (\S+), contactInfo)
- print match #[(Doe, John, 555-1212)]
来源: http://www.bubuko.com/infodetail-2524572.html