python中关于或的正则表达式

程柏勳*_*程柏勳 2 python regex python-2.7

我知道p=re.compile('aaa|bbb')可以使用,但是我想p = re.compile('aaa|bbb')使用变量进行重写,例如

A = 'aaa'
B = 'bbb'
p = re.compile(A|B)
Run Code Online (Sandbox Code Playgroud)

但这不起作用。我该如何重写它以便使用变量(并且可以工作)?

ale*_*cxe 5

p=re.compile(A|B)

您没有正确执行字符串连接。您正在执行的操作是将“按位或”(管道)运算符应用于字符串,这当然会失败:

>>> 'aaa' | 'bbb'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'str' and 'str'
Run Code Online (Sandbox Code Playgroud)

相反,您可以使用str.join()

p = re.compile(r"|".join([A, B])) 
Run Code Online (Sandbox Code Playgroud)

演示:

>>> A = 'aaa'
>>> B = 'bbb' 
>>> r"|".join([A, B])
'aaa|bbb'
Run Code Online (Sandbox Code Playgroud)

并且,请确保您信任AB(注意Regex注入攻击)的来源,和/或适当地避免它们。