正则表达式,用于测试字符串的可能值的有限调色板



我需要一个正则表达式来测试字符串是否位于特定的值调色板中,例如字符串dir ca 只能是 ltrrtllrorlo ,或者另一个示例bool只能是 falsetrue

我可以使用什么正则表达式来针对有限的一组值测试 dirbool 等字符串?

比正则表达式更好,使用列表或集合。

dir_choice = set(('ltr', 'rtl', 'lro', 'rlo'))
if dir in dir_choice:
    ...

(如果之前定义了dir_choice,则检查速度比编译的正则表达式快六倍 @IvanKoblik)

bool_choice = set(('true', 'false'))
if bool in bool_choice:
    ...

你的意思是像'^(ltr|rtl|lro|rlo)$''^(true|false)$'

这甚至可以轻松实现自动化:

def make_re(args):
    args = (re.escape(arg) for arg in args) #if you want to escape special characters
    return re.compile('^({0})$'.format('|'.join(args)) )
boolre = make_re(('true','false'))

但是,如果您将线路args = (re.escape(arg) ...)留在那里,那么您真的不会获得任何超出使用 if arg in myset: ... 所能获得的任何东西。 未转义版本的美妙之处在于您仍然至少具有一些正则表达式灵活性。

要检查 dir 是否等于这些字符串之一,您可以使用以下内容:

re.match("^(ltr|rtl|lro|rlo)$", dir)

另一个用于布尔值:

re.match("^(false|true)$", bool)

除非您遵循更好的建议并为此目的使用哈希集。