簡體   English   中英

Python 正則表達式匹配子字符串

[英]Python Regex Match sub-string

我有以下字符串:

spf=pass (sender IP is 198.71.245.6) smtp.mailfrom=bounces.em.godaddy.com; domainname.com.au; dkim=pass (signature was verified) header.d=godaddy.com;domainname.com.au; dmarc=pass action=none header.from=godaddy.com;

使用以下代碼:

if "Authentication-Results" in n:
    auth_results = n['Authentication-Results']
    print(auth_results)

    spf = re.match(r"spf=(\w+)", auth_results)
    if spf:
       spf_result = spf.group(1)

    dkim = re.match(r"^.*dkim=(\w+)", auth_results)
    print(dkim)
    if dkim:
        dkim_result = dkim.group(1)

SPF 始終匹配,但 DKIM 不匹配:

print(dkim) = None

根據在線正則表達式測試人員的說法,它應該: https : //regex101.com/r/ZkVg74/1任何想法為什么不是我也嘗試過這些:

dkim = re.match(r"dkim=(\\w+)", auth_results) dkim = re.match(r"^.*dkim=(\\w+)", auth_results, re.MULTILINE)

. 默認情況下不匹配換行符。 由於測試字符串中的dkim位於第二行,並且您的正則表達式模式嘗試將字符串開頭的任何非換行符與^.*匹配,因此它不會在第二行找到dkim 您應該使用re.DOTALL標志來允許. 匹配換行符:

dkim = re.match(r"^.*dkim=(\w+)", auth_results, flags=re.DOTALL)

或者從字符串的開頭完全刪除不必要的匹配:

dkim = re.search(r"dkim=(\w+)", auth_results)

首先, re.match從一開始就起作用。 所以你的r"dkim=(\\w+)"試驗不起作用。

其次, . 符號匹配除換行符以外的字符。 如果您願意,您應該使用re.Sre.DOTALL標志re.S強制它。

此外,您可以使用[\\s\\S][\\w\\W]來匹配任何字符。

嘗試這個:
re.match(r"^[\\s\\S]*dkim=(\\w+)", auth_results).group(1)
或這個:
re.match(r"^.*dkim=(\\w+)", auth_results, re.DOTALL).group(1)

暫無
暫無

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

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