美文网首页生活不易 我用python
说说在 Python 中,如何找出所有字符串匹配

说说在 Python 中,如何找出所有字符串匹配

作者: deniro | 来源:发表于2019-12-14 11:51 被阅读0次

Regex 对象有一个 findall() 方法,它会返回包含所查找字符串的所有匹配。这与 search() 方法明显不同,search() 将返回一个 Match 对象,其中包含被查找字符串中的 “ 第一次 ” 匹配文本。请看以下示例,注意区分:

phone_num_regex = re.compile(r'\d\d\d\d-\d\d\d\d\d\d\d\d')
mo = phone_num_regex.search('我的联系号码为: 0591-83822032;另一个号码是:0591-83822033.')
print('查到的联系号码: ' + mo.group())

phone_num_regex = re.compile(r'\d\d\d\d-\d\d\d\d\d\d\d\d')
phone_nums = phone_num_regex.findall('我的联系号码为: 0591-83822032;另一个号码是:0591-83822033.')
print('查到的联系号码: ' + str(phone_nums))

运行结果:

查到的联系号码: 0591-83822032
查到的联系号码: ['0591-83822032', '0591-83822033']

如果调用 findall 的正则表达式不存在分组(比如上例),那么方法 findall() 将返回一个匹配字符串的列表,例如上例的 ['0591-83822032', '0591-83822033']。

如果调用 findall 的正则表达式存在分组,那么方法 findall() 将返回一个字符串元组的列表(每个分组对应一个字符串),请看下例:

phone_num_regex = re.compile(r'(\d\d\d\d)-(\d\d\d\d\d\d\d\d)')
phone_nums = phone_num_regex.findall('我的联系号码为: 0591-83822032;另一个号码是:0591-83822033.')
print('查到的联系号码: ' + str(phone_nums))

运行结果:

查到的联系号码: ['0591-83822032', '0591-83822033']
查到的联系号码: [('0591', '83822032'), ('0591', '83822033')]

相关文章

网友评论

    本文标题:说说在 Python 中,如何找出所有字符串匹配

    本文链接:https://www.haomeiwen.com/subject/stecnctx.html