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

如何从给定String中提取并打印指定的第2、第3行

从多行字符串打印指定行的实现方案

待处理原始字符串:

"
test

 test

 test

 test"

需求:打印上述字符串的第2、3行

Python 实现

raw_str = """
test

 test

 test

 test"""
# splitlines() 自动兼容不同系统换行符,分割为行列表
lines = raw_str.splitlines()
# 行号从1计数时,第2、3行对应索引1、2,切片左闭右开
for line in lines[1:3]:
    print(line)

Java 实现

public class GetTargetLines {
    public static void main(String[] args) {
        String rawStr = "\ntest\n\n test\n\n test\n\n test";
        // \\R 匹配任意类型换行符
        String[] lines = rawStr.split("\\R");
        // 输出第2、3行
        System.out.println(lines[1]);
        System.out.println(lines[2]);
    }
}

Shell 命令行实现

raw_str=$'\ntest\n\n test\n\n test\n\n test'
# sed 默认行号从1开始计数,-n关闭默认输出,2,3p打印第2到第3行
echo "$raw_str" | sed -n '2,3p'

注意事项

  • 注意行号的计数基准:编程语言的列表/数组索引默认从0开始,sed、awk等命令行工具行号默认从1开始,需要根据你的计数规则调整取值范围
  • 换行分割优先选择兼容多系统换行符的方法,避免不同操作系统下换行符格式差异导致的分割错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:15:08