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

不使用正则表达式提取字符串中((与))间内容的方法

不使用正则提取指定标记间内容的方法

针对字符串 "((the)) weather is usually good ((when)) its ((spring))",可以通过字符串的查找与截取方法实现,步骤如下:

  • 初始化空列表存储提取结果,设置初始查找位置为0
  • 循环执行以下操作:
    1. 从当前位置开始查找标记 (( 的起始索引
    2. 若找不到 ((,直接跳出循环
    3. 从找到的 (( 索引+2的位置开始,查找对应 )) 的起始索引
    4. 若找到 )),截取 (( 结束到 )) 开始之间的子串,加入结果列表
    5. 更新当前查找位置为 )) 索引+2的位置,继续下一轮查找

用Python代码实现的示例:

s = "((the)) weather is usually good ((when)) its ((spring))"
result = []
start = 0
while True:
    open_tag = s.find('((', start)
    if open_tag == -1:
        break
    close_tag = s.find('))', open_tag + 2)
    if close_tag == -1:
        break
    content = s[open_tag+2 : close_tag]
    result.append(content.strip())  # 可选:去除内容前后可能的空格
    start = close_tag + 2

print(result)  # 输出: ['the', 'when', 'spring']

这个方法通过逐次定位标记位置,手动截取目标内容,完全不需要依赖正则表达式。

内容的提问来源于stack exchange,提问作者user20137453

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:50:34