我真的很难接受这一点.我试着从左往右找,但还是想不通.

我有一个字符串列表,带有随机数量的标签,每个标签放在括号中,随机放置在每个字符串中.下面几个例子可能如下所示.

[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]设置一个例外,并且真的搞不清楚.如果您能帮忙,我们将不胜感激. 谢谢.

推荐答案

仅当第一个括号后面没有您不需要的标记时才匹配它:

import re

lines = '''\
[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)'''.splitlines()

for line in lines:
    print(re.sub(r'\[(?!Animations?\]).*?\]', '', line).strip())

输出:

Desired string - with optional dash
Desired string
Desired - string (with suffix)
[Animation] Target string
[Animations](prefix)Desired - string (and suffix)

Python相关问答推荐

Python:在类对象内的字典中更改所有键的索引,而不是仅更改一个键

将图像拖到另一个图像

大小为M的第N位_计数(或人口计数)的公式

当从Docker的--env-file参数读取Python中的环境变量时,每个\n都会添加一个\'.如何没有额外的?

为什么以这种方式调用pd.ExcelWriter会创建无效的文件格式或扩展名?

如何创建一个缓冲区周围的一行与manim?

未知依赖项pin—1阻止conda安装""

为什么numpy. vectorize调用vectorized函数的次数比vector中的元素要多?

剪切间隔以添加特定日期

将CSS链接到HTML文件的问题

如何将相同组的值添加到嵌套的Pandas Maprame的倒数第二个索引级别

如何将泛型类类型与函数返回类型结合使用?

你能把函数的返回类型用作其他地方的类型吗?'

如何在Python中自动创建数字文件夹和正在进行的文件夹?

SpaCy:Regex模式在基于规则的匹配器中不起作用

高效生成累积式三角矩阵

无法在盐流道中获得柱子

如何批量训练样本大小为奇数的神经网络?

多个布尔条件的`jax.lax.cond`等效项

为什么在安装了64位Python的64位Windows 10上以32位运行?