Skip to main content
 首页 » 编程设计

python之python 中的正则表达式使用 OR 表示单引号或双引号

2025年05月04日28sky-heaven

我正在尝试在 python 中为这些示例中的单引号或双引号编写正则表达式:

动物="猫"

动物="马"

动物='狗'

动物='牛'

尝试使用 | 时它是空的

re.compile("animal=\"|'(.+?)\"|'").findall 

请帮忙。谢谢

请您参考如下方法:

您可以利用反向引用:

r = re.compile(r"""animal=(["'])(.+?)\1""") 

这保证了开始和结束字符是相同的。

是时候测试它了:

assert r.search('animal="cat"').group(2) == "cat" 
assert r.search('animal="horse"').group(2) == "horse" 
assert r.search("animal='dog'").group(2) == "dog" 
assert r.search("animal='cow'").group(2) == "cow"