📌  相关文章
📜  在Python中使用正则表达式提取电子邮件地址

📅  最后修改于: 2022-05-13 01:55:20.295000             🧑  作者: Mango

在Python中使用正则表达式提取电子邮件地址

假设您必须读取一些特定数据,例如电话号码、电子邮件地址、日期、单词集合等。您如何以非常有效的方式做到这一点?通过正则表达式做到这一点的最佳方法。

举个例子,我们必须通过正则表达式从给定的输入中只找出电子邮件。
例子:

Input  : Hello shubhamg199630@gmail.com Rohit neeraj@gmail.com
Output : shubhamg199630@gmail.com neeraj@gmail.com
Here we have only selected email from the given input string.

Input : My 2 favourite numbers are 7 and 10
Output :2 7 10
Here we have selected only digits.

正则表达式
正则表达式是一个字符序列,主要用于查找和替换字符串或文件中的模式。
所以我们可以说搜索和提取任务是如此普遍,以至于Python有一个非常强大的库,称为正则表达式,可以非常优雅地处理其中的许多任务。

SymbolUsage
$Matches the end of the line
\sMatches whitespace
\SMatches any non-whitespace character
*Repeats a character zero or more times
\SMatches any non-whitespace character
*?Repeats a character zero or more times (non-greedy)
+Repeats a character one or more times
+?Repeats a character one or more times (non-greedy)
[aeiou]Matches a single character in the listed set
[^XYZ]Matches a single character not in the listed set
[a-z0-9]The set of characters can include a range
(Indicates where string extraction is to start
)Indicates where string extraction is to end
# Python program to extract numeric digit 
# from A string by regular expression...
  
# Importing module required for regular
# expressions
import re  
  
# Example String 
s = 'My 2 favourite numbers are 7 and 10'
  
# find all function to select all digit from 0   
# to 9 [0-9] for numeric Letter in the String
# + for repeats a character one or more times
lst = re.findall('[0-9]+', s)    
  
# Printing of List
print(lst)
输出:
['2', '7', '10']
# Python program to extract emails From 
# the String By Regular Expression. 
  
# Importing module required for regular 
# expressions 
import re 
  
# Example string 
s = """Hello from shubhamg199630@gmail.com
        to priya@yahoo.com about the meeting @2PM"""
  
# \S matches any non-whitespace character 
# @ for as in the Email 
# + for Repeats a character one or more times 
lst = re.findall('\S+@\S+', s)     
  
# Printing of List 
print(lst) 
输出:
['shubhamg199630@gmail.com', 'priya@yahoo.com']

更多细节:

  • Python中的正则表达式与示例|设置 1
  • Python中的正则表达式 |第 2 组(搜索、匹配和查找全部)
  • 正则表达式的Python文档