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

如何使用Golang循环拆分重复格式的字符串并逐行输出?

解决方法

核心思路

目标是提取所有以xx开头、yy结尾的连续片段,然后逐个输出。最直接的方式是用正则匹配,或者手动遍历字符串定位片段边界。

方法1:正则匹配(推荐)

利用正则的非贪婪匹配特性,精准捕获每个xx...yy片段:

Python 实现

import re

original_str = "xx5645645yyxx9879869yyxx3879870977yy"
# 匹配所有xx开头、yy结尾的片段,非贪婪模式确保只捕获到最近的yy
segments = re.findall(r'xx.*?yy', original_str)
# 循环输出每个片段
for seg in segments:
    print(seg)

JavaScript 实现

const originalStr = "xx5645645yyxx9879869yyxx3879870977yy";
// 全局匹配所有xx到yy的片段
const segments = originalStr.match(/xx.*?yy/g);
// 循环打印结果
segments.forEach(seg => console.log(seg));

方法2:手动遍历字符串(无需正则)

如果不想用正则,可以通过遍历字符串定位每个片段的起始和结束位置:

original_str = "xx5645645yyxx9879869yyxx3879870977yy"
segments = []
current_pos = 0
str_length = len(original_str)

while current_pos < str_length:
    # 定位下一个xx的起始位置
    if original_str[current_pos:current_pos+2] != "xx":
        current_pos += 1
        continue
    # 找到当前xx对应的yy的结束位置
    yy_pos = original_str.find("yy", current_pos + 2)
    if yy_pos == -1:
        break
    # 截取片段并保存
    segments.append(original_str[current_pos:yy_pos+2])
    # 移动到下一个片段的起始位置
    current_pos = yy_pos + 2

# 循环输出结果
for seg in segments:
    print(seg)

以上两种方法都能得到你想要的输出结果:

xx5645645yy
xx9879869yy
xx3879870977yy

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:25:30