我真的很难接受这一点.我试着从左往右找,但还是想不通.
我有一个字符串列表,带有随机数量的标签,每个标签放在括号中,随机放置在每个字符串中.下面几个例子可能如下所示.
[tag1][tag4] Desired string - with optional dash [tag10]
[tag1][tag2][tag3] Desired string [tag10]
[tag3][tag1][tag2][tag5] Desired - string (with suffix)
[tag2][tag5][tag4] [Animation] Target string [tag10]
[tag3][tag1][tag5][tag10][Animations](prefix)Desired - string (and suffix)
我想要实现的是从每个字符串中提取不带标记的内容,并将其括在括号中.唯一的例外是标签[Animation]或[Animations].如果出现这些标记之一,我希望将它们与所需的字符串一起提取出来.
因此,在上面列出的情况下,期望的输出将如下所示.(我不关心提取的字符串周围的空格,它将在之后被修剪.)
Desired string - with optional dash
Desired string
Desired - string (with suffix)
[Animation] Target string
[Animations](prefix)Desired - string (and suffix)
最初,我使用的是与\[.*?\]
一样简单的正则表达式.它匹配括号中的所有标记,我只需将所有内容替换为空字符串.
re_pattern = r"\[.*?\]"
re.sub(re_pattern, '', dirty_string).strip()
然而,现在我发现有必要为标签[Animation]和[Animations]设置一个例外,并且真的搞不清楚.如果您能帮忙,我们将不胜感激. 谢谢.