python中findall函数怎么调用

869
2023/11/26 16:47:06
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,可以使用re模块中的findall()函数来查找字符串中的所有匹配项。

语法: re.findall(pattern, string, flags=0)

参数说明:

  • pattern: 匹配的正则表达式
  • string: 要匹配的字符串
  • flags: 可选参数,用于控制正则表达式的匹配方式,默认为0表示不使用任何标志

示例代码:

import re

text = "Hello, my name is John. My email address is john@example.com. My friend's email is mary@example.com."
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)

for email in emails:
    print(email)

输出结果:

john@example.com
mary@example.com

在上面的示例中,使用了正则表达式来匹配字符串中的电子邮件地址。re.findall()函数返回一个列表,包含了所有匹配到的电子邮件地址。然后使用for循环遍历列表,并打印每个电子邮件地址。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python怎么终止线程池中的线程