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

Python中无需正则,如何获取所有目标匹配子串列表?

不用正则的解决方案

嘿,不用正则其实超容易实现的!我们换个思路,既然你要的是从开头逐步累加包含每个"and"的完整子串,直接拆分再逐步拼接就搞定啦,步骤如下:

  • 首先把原字符串用" and "作为分隔符拆分,这样就能得到每个被"and"隔开的独立片段:
    s = "I like lettuce and carrots and onions"
    parts = s.split(" and ")
    # 拆分后得到: ["I like lettuce", "carrots", "onions"]
    
  • 接着初始化一个空的结果列表,再准备一个临时变量用来逐步拼接子串
  • 最后遍历拆分后的每个片段,每次把当前片段拼到临时变量里(第一次直接赋值,后续要加上分隔符" and "),然后把拼接好的字符串加入结果列表:
    result = []
    current_str = ""
    for part in parts:
        if current_str:
            current_str += " and " + part
        else:
            current_str = part
        result.append(current_str)
    
    print(result)
    # 输出: ["I like lettuce", "I like lettuce and carrots", "I like lettuce and carrots and onions"]
    

这样就能完美得到你想要的三个匹配结果啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:48:01