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

标签 python regex python-2.7

我需要一个正则表达式来测试字符串是否在特定的值调色板中,例如字符串 dir 只能是 ltrrtl , lro, rlo, 或者另一个例子 bool 只能是false, true .

我可以使用什么正则表达式来针对一组有限的值测试像 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:
    ...

关于python - 用于测试字符串的可能值的有限调色板的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12514802/

相关文章:

django - 遇到未知标签 'with'

python - 收集列表以查找两个列表 python 中的区别

python - QGraphicsAnchorLayout 未锚定在 QGraphicsScene 中

python:将 "5,4,2,4,1,0"转换为 [[5, 4], [2, 4], [1, 0]]

python - DNSQR 是什么?

PHP preg_replace : unicode modifier for ascii strings

javascript - javascript 中的 '/' 是如何工作的?

python - 是否可以在 __post_init__() 或更高版本中卡住数据类对象?

regex - 正则表达式可能无法使用正则表达式在Google Analytics(分析)中运行?

python - 类型错误 : Odd-length string when decoding hex string