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

时间:2019-05-28 13:37:31

标签: python powershell email wildcard

我目前正在从事电子邮件收件箱自动化项目,并且正在尝试使用通配符查找某些电子邮件主题。电子邮件中有时会随机生成票证编号,因此我需要对此进行补偿。这是我在PowerShell中编写它的方式。

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

这将触发每封主题行为Test Number:的电子邮件,而不管其后随机生成的数字如何。

从我所看到的情况来看,Python并不只是像PowerShell具有-like*这样的通配符。那或者我愚蠢,找不到它。我所看到的唯一一件事涉及安装模块以使通配符起作用。 Python有内置通配符吗?

1 个答案:

答案 0 :(得分:3)

在您的情况下,您可以使用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)

注意:

  • substring *等效于string.startsWith(substring)
  • *子字符串等效于string.endswith(substring)
  • * substring *等效于substring in string

如果您有一些更复杂的模式,建议您使用re模块。例如,您要匹配每个:'Test: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之间)
  • $结束符