繁体   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