gpt4 book ai didi

python - python 中关于或的正则表达式

转载 作者:行者123 更新时间:2023-11-28 21:46:21 26 4
gpt4 key购买 nike

我知道 p=re.compile('aaa|bbb') 可以工作,但我想重写 p = re.compile('aaa|bbb') 使用变量,比如

A = 'aaa'
B = 'bbb'
p = re.compile(A|B)

但这行不通。我如何重写它以便使用变量(并且它有效)?

最佳答案

p=re.compile(A|B)

您没有正确进行字符串连接。你正在做的是应用 "bitwise or" (the pipe) operator到字符串,这当然会失败:

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

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

p = re.compile(r"|".join([A, B])) 

演示:

>>> A = 'aaa'
>>> B = 'bbb'
>>> r"|".join([A, B])
'aaa|bbb'

并且,确保您信任 AB 的来源(提防 Regex injection attacks ),或者/和正确地 escape他们。

关于python - python 中关于或的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38135354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com