Findall模式使用python re

2024-09-19 23:27:20 发布

您现在位置:Python中文网/ 问答频道 /正文

提前感谢
我想在re中找到某种模式。我尝试了不同的组合,这就是我所处的位置。
代码如下:

import re

txt = "Suggested Profile(s) : Win7SP1x64, Win7SP0x64, Win2008R2SP1x64, Win7SP1x64_24000, Win2008R2x32, Win7x32"

match = re.findall(r"Win.+64", txt)

if match:
    y = match[0]

try:
    profiles = y.split(", ")

    for profile in profiles:
        print(profile)
except Exception:
    print("Error")

运行此操作时,我得到以下输出:

Win7SP1x64
Win7SP0x64
Win2008R2SP1x64
Win7SP1x64

这有点正确,但它没有显示完整的输出。最后一个单词“Win7SP1x64”不完整,它是“Win7SP1x64_24000”,但在输出中,它只显示到“64”。
另外,我希望脚本也显示带有“32”的单词,但不确定如何实现


Tags: 代码importretxtmatch模式profileprofiles
2条回答

您还需要匹配64之后的尾随字符。您指定的正则表达式仅在64之前有效

从您的解决方案中,您可以这样做:

match_64 = re.findall(r"Win\w+64\w*", txt)

32人

match_32 = re.findall(r"Win\w+x32\w*", txt)

我想您正在寻找类似r“Win[^,]+x[2346][\ud]*”

txt = "Suggested Profile(s) : Win7SP1x64, Win7SP0x64, Win2008R2SP1x64, Win7SP1x64_24000, Win2008R2x32, Win7x32"

match = re.findall(r"Win[^,]+x[2346][_\d]*", txt)

匹配变量将包含:

['Win7SP1x64', 'Win7SP0x64', 'Win2008R2SP1x64', 'Win7SP1x64_24000', 'Win2008R2x32', 'Win7x32']

相关问题 更多 >