簡體   English   中英

使用 Python 正則表達式匹配字母數字單詞、提及或電子郵件

[英]Matching alphanumeric words, mentions or emails with Python regex

我已經讀過這個這個這個以及很多其他的。 他們不回答我的問題。

我想過濾一個字符串,它可能包含以“@”開頭的電子郵件字符串(如電子郵件,但在“@”之前沒有文本)。 我已經測試了很多,但開始接近的最簡單的方法之一是:

import re
re.split(r'(@)', "test @aa test2 @bb @cc t-es @dd-@ee, test@again")
Out[40]: 
['test ', '@', 'aa test2 ', '@', 'bb ', '@', 'cc t-es ', '@', 'dd-', '@', 'ee, test', '@', 'again']

我正在尋找可以給我的正確正則表達式:

['test ', '@aa', 'test2 ', '@bb ', '@cc', 't-es ', '@dd-', '@ee', 'test@again']

當您可以“喲正則表達式,給我所有匹配項”時,為什么要嘗試拆分:

test = "test @aa test2 @bb @cc t-es @dd-@ee, test@again"


import re

print(
    re.findall("[^\s@]*?@?[^@]* |[^@]*@[^\s@]*", test)
)
# ['test ', '@aa test2 ', '@bb ', '@cc t-es ', '@dd-', '@ee, ', 'test@again']

我試過了,但我不能讓正則表達式更小,但至少它有效,而且誰希望正則表達式很小


根據 OP 的新要求(或更正的要求)

[^\s@]*?@?[^\s@]* |[^@]*@[^\s@]* 

我自己的基於不同電子郵件解析+簡單“ @[:alphanum:]+ ”解析的解決方案是:

USERNAME_OR_EMAIL_REGEX = re.compile(
    r"@[a-zA-Z0-9-]+"  # simple username
    r"|"
    r"[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+"  # email 
    r"@"  # following: domain name:
    r"[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?"
    r"(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM