繁体   English   中英

如何从括号中删除字符串,包括带有条件的括号?

[英]How to remove a string from brackets including the brackets with a condition?

我有一个与此类似的问题。

我想删除括号和其中的文字,但保留一些文字。 例如我有一个列表:

["Going", "(#)", "(maybe)", "to", "the", "(##)", "(mall)", "market"]

我想保留(#)(##) ,但删除(maybe)(mall)

预期输出:

["Going", "(#)", "to", "the", "(##)", "market"]

列表中可以有任意数量的带括号的单词,例如'maybe''mall'

#的括号最多可以有 3 个哈希。

您可以使用列表理解来使用正则表达式过滤原始列表:

import re

a = ["Going", "(#)", "(maybe)", "to", "the", "(##)", "(mall)", "market"]
b = [word for word in a if re.match(r"[^(]|\(#{1,3}\)", word)]

给出:

['Going', '(#)', 'to', 'the', '(##)', 'market']

re.match匹配字符串开头的模式。 图案的意思是:

  • [^(] -(之外的任何字符。
  • | - 或者...
    • \( - 文字括号
    • #{1,3} - 1 到 3 次重复#
    • \) - 文字括号

正则表达式演示

以一种通用的方式,您可以解析列表并评估该单词是否有一对括号。 如果是这样,并且里面的单词不是#、## 或 ### ,那么您应该将其从输出中排除。 假设您有一个字符串列表:

a = ['Going', '(#)', '(maybe)', 'to', 'the', '(##)', '(mall)', 'market']

output = [word for word in a if ('(' not in word and ')' not in word) or word.strip('()') in ['#', '##', '###']]
print(output)
# ['Going', '(#)', 'to', 'the', '(##)', 'market']

strip方法只保留给定参数中的字符串(在本例中为() )。

您可以在此处了解有关列表推导的更多信息:https ://www.w3schools.com/python/python_lists_comprehension.asp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM