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

Java中如何用字符串函数快速提取第3、4个冒号间的子串?

Java提取指定冒号间子串的简便方法

针对你给出的固定格式字符串,这里有几种实用的实现方式:

方法一:用indexOf定位截取

通过多次调用indexOf精准找到第3个和第4个冒号的位置,再用substring截取中间内容,无需额外依赖,性能可控:

public static String extractTargetSubstring(String str) {
    // 依次定位第1到第4个冒号的位置
    int colon1 = str.indexOf(':');
    int colon2 = str.indexOf(':', colon1 + 1);
    int colon3 = str.indexOf(':', colon2 + 1);
    int colon4 = str.indexOf(':', colon3 + 1);
    
    return str.substring(colon3 + 1, colon4);
}

调用示例:

String[] testStrings = {"ab:ab:ab:1:ab", "ac:ac:ac:2:ac", "ad:ad:ad:3:ad"};
for (String s : testStrings) {
    System.out.println(extractTargetSubstring(s));
}

输出结果:1、2、3

方法二:用split分割数组

如果字符串格式完全固定(确保每个字符串都有至少4个冒号),直接用split按冒号分割后取对应索引的元素,代码最简洁:

public static String extractWithSplit(String str) {
    String[] segments = str.split(":");
    // 做长度校验避免数组越界
    return segments.length >= 4 ? segments[3] : "";
}

方法三:用正则表达式匹配

适合需要更灵活匹配规则的场景,通过正则捕获第3、4个冒号之间的内容:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public static String extractWithRegex(String str) {
    Pattern pattern = Pattern.compile("^[^:]+:[^:]+:[^:]+:([^:]+):");
    Matcher matcher = pattern.matcher(str);
    return matcher.find() ? matcher.group(1) : "";
}

正则说明:^[^:]+:匹配前三个冒号分隔的前缀,([^:]+)精准捕获目标子串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:15:17