匹配字符串和提取部分

2024-04-27 05:04:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题。我有一个字符串,我想提取它的一部分使用正则表达式。这是绳子

{名字}我爱我的作品{英雄}

我想提取

[{{name}}, {{hero}}]

同样在字符串作为

{名字}我爱我一些作品{英雄,进来{这里,这就是}

我还是想得到

[{{name}, {{name, {here, right}]

我希望这有道理。我在用Python。你知道吗


Tags: 字符串namerighthere名字作品hero绳子
2条回答

如果您想要['{{name}}', '{{hero}}', '{{hero, come in {here, this is right}'],请使用@Avinash的regex。你知道吗

如果需要['{{name}}', '{{hero}}', '{{hero', {here', 'right}'],请使用以下命令:

re.findall(r'{+\w+}*|{*\w+}+', s)

RegEX DEMO

你试过以下方法吗?你知道吗

import re
s = '{{name} I love me some work {{hero, come in {here, this is right}'
print re.findall(r'\{.*?\}', s)

相关问题 更多 >