Python 有类似于 PowerShell 的通配符吗?

Does Python Have a Wildcard Similar to PowerShell?

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

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

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

据我所见,Python 并不像 PowerShell 具有 -like* 那样简单地具有通配符。那或者我很笨,找不到它。我看到的唯一一件事涉及安装模块以使通配符起作用。 Python 有内置通配符吗?

您可以根据自己的情况使用 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)
  • *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到1的数字5(表示介于 20 和 25 之间)
  • $ 结束符