欢迎访问宙启技术站
智能推送

findall()函数使用方法

发布时间:2023-06-25 17:54:54

findall()函数是Python中re模块(正则表达式)提供的一个函数,它可以在字符串中搜索所有与正则表达式匹配的子串,并返回一个包含所有匹配结果的列表,如果没有匹配则返回一个空列表。

语法:

re.findall(pattern, string, flags=0)

参数说明:

pattern:正则表达式

string:需要匹配的字符串

flags:可选参数,表示匹配模式,通常是正则表达式中的一些特殊字符。

findall()函数返回一个列表,其中包含所有正则表达式与string匹配的所有非重叠的字符串。

下面是一个例子来说明findall()函数的用法:

我们要找出字符串中所有的数字,可以使用正则表达式:\d+。

import re

str = "hello123, world! 4567"

num = re.findall('\d+', str)

print(num) 

#output: ['123', '4567']

在上面的例子中,用re模块进行字符串中数字提取,返回一个包含数字123和4567的列表。

下面是一些常用的正则表达式来讲解findall()函数的用法:

1.匹配字母

import re

str = "Hello, Python!"

letters = re.findall('[a-zA-Z]+', str)

print(letters)

#output: ['Hello', 'Python']

上述正则表达式[a-zA-Z]+表示匹配所有大写字母A-Z及小写字母a-z。

2.匹配数字

import re

str = "Jenny's phone number is 1808888888"

numbers = re.findall('\d+', str)

print(numbers)

#output: ['1808888888']

上述正则表达式\d+表示匹配所有数字。

3.匹配IP地址

import re

str = "My IP address is 192.168.1.1"

ip = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', str)

print(ip)

#output: ['192.168.1.1']

上述正则表达式\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}表示匹配所有IP地址。

4.匹配URL链接

import re

str = "This is a link to: https://www.google.com"

url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', str)

print(url)

#output: ['https://www.google.com']

上述正则表达式https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+表示匹配所有URL链接。

5.匹配邮箱地址

import re

str = "My email is jenny@gmail.com"

email = re.findall('[\w\.-]+@[\w\.-]+', str)

print(email)

#output: ['jenny@gmail.com']

上述正则表达式[\w\.-]+@[\w\.-]+表示匹配所有邮箱地址。

总之,findall()函数在文本中搜索所有符合正则表达式条件的内容,然后将所有搜索到的结果保存在一个列表中返回。它能够快速有效地处理文本数据,有助于我们在实际开发过程中处理文本数据。