Python是否有类似于PowerShell的通配符?

2024-04-20 01:30:18 发布

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

我目前正在进行一个电子邮件收件箱自动化项目,我正在尝试使用通配符来查找某些电子邮件主题。电子邮件有时会随机生成票号,所以我需要对此进行补偿。下面是我如何在PowerShell中编写的。你知道吗

if($email.'Subject' -like 'Test Number:*') {...}

这将为主题行为Test Number:的每封电子邮件触发,而不考虑下面随机生成的数字。你知道吗

在我看来,Python并不像PowerShell那样有一个通配符-like*。不然我就哑巴找不到了。我看到的唯一一件事就是安装模块来让通配符工作。Python有内置的通配符吗?你知道吗


Tags: 项目testnumber主题if电子邮件email数字
1条回答
网友
1楼 · 发布于 2024-04-20 01:30:18

在您的案例中可以使用startswith

email_subjects = ['Test:1', 'Test:25', 'not_valid!']
for email_subject in email_subjects:
    if email_subject.startswith('Test:'):
        print('valid email subjet', email_subject)
    else:
        print('invalid email subjet', email_subject)

对于注释:

  • 子串*等价于string.startsWith(substring)
  • *子串等价于string.endswith(substring)
  • *子串*等价于substring in string

如果您有一些更复杂的模式,我建议您使用re模块。例如,您希望将每个:'Test:X与X匹配,X是介于125之间的数字

import re

email_subjects = ['Test:1', 'Test:25', 'not_valid!', 'Test:52']
for email_subject in email_subjects:
    if re.search(''^Test:([0-9]|1[0-9]|2[0-5])$'', email_subject): # Compiles to a regular expression and looks for it in email_subject
        print('valid email subjet', email_subject)
    else:
        print('invalid email subjet', email_subject)

正则表达式细分:

  • ^开始字符匹配
  • Test:要匹配的字符串
  • ([0-9]|1[0-9]|2[0-5]):你的范围,意思是:0到9之间的数字,或者1和0到9之间的数字(意思是10到19之间),或者2和0到5之间的数字(意思是20到25之间)
  • $结束字符

相关问题 更多 >