You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正则表达式实现:提取目标字符串并保留指定括号标签

正则表达式:保留指定括号标签,移除其他所有括号标签

可以使用负向预查来排除需要保留的标签,只匹配并移除其他括号标签。对应的正则表达式和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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 17:03:20