正则表达式实现:提取目标字符串并保留指定括号标签
正则表达式:保留指定括号标签,移除其他所有括号标签
可以使用负向预查来排除需要保留的标签,只匹配并移除其他括号标签。对应的正则表达式和Python代码如下:
import re re_pattern = r"\[(?!Animation(s)?\]).*?\]" test_strings = [ "[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)" ] for s in test_strings: cleaned = re.sub(re_pattern, '', s).strip() print(cleaned)
正则表达式解释
\[:匹配左方括号[(转义是因为[在正则中属于特殊字符)(?!Animation(s)?\]):负向预查断言,确保括号内的内容不是Animation或Animations:Animation(s)?匹配Animation或Animations((s)?表示s为可选字符)\]匹配右方括号,保证断言的是完整目标标签
.*?:非贪婪匹配括号内的任意字符,避免跨标签的过度匹配\]:匹配右方括号]
运行输出
Desired string - with optional dash Desired string Desired - string (with suffix) [Animation] Target string [Animations](prefix)Desired - string (and suffix)
完全符合预期处理结果。
内容的提问来源于stack exchange,提问作者Broomstick
相关产品推荐
相关产品推荐

