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

Java中如何截取两个特殊字符间的子串?split代码问题求助

Hey there, let's fix this string extraction issue step by step!

First off, your original split code won't work at all—Java's String.split() method doesn't accept two separator strings as parameters. Its valid overloads are either split(String regex) or split(String regex, int limit), so split("\\]" , "\\[") will throw a compile error right away.

Here are three reliable ways to extract the substring "123456" from your target string:

方法1:正则表达式匹配(最直观,适配复杂格式)

Use Pattern and Matcher to target the content wrapped between [ and ]—this approach is readable and easy to adjust if your string format changes slightly later:

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

public class StringExtractDemo {
    public static void main(String[] args) {
        String code = "[123456]Ahmed";
        // Regex rule: match [, then capture any non-] characters until ]
        Pattern pattern = Pattern.compile("\\[(.*?)\\]");
        Matcher matcher = pattern.matcher(code);
        
        if (matcher.find()) {
            String target = matcher.group(1); // Grab the first captured group
            System.out.println(target); // Output: 123456
        }
    }
}
方法2:indexOf + substring(性能最优,适合固定简单格式)

If your string will always follow the [xxx]yyyy pattern, directly locating indices is the most efficient way—no regex engine overhead:

public class StringExtractDemo {
    public static void main(String[] args) {
        String code = "[123456]Ahmed";
        int startIdx = code.indexOf('[') + 1; // Skip the [ character
        int endIdx = code.indexOf(']'); // Find the closing ]
        
        // Add checks to avoid index out-of-bounds errors for invalid formats
        if (startIdx > 0 && endIdx > startIdx) {
            String target = code.substring(startIdx, endIdx);
            System.out.println(target); // Output: 123456
        }
    }
}
方法3:间接用split实现(如果你执意想用split)

While split doesn't support two separators directly, you can chain splits to get the desired result:

public class StringExtractDemo {
    public static void main(String[] args) {
        String code = "[123456]Ahmed";
        // Split by [ first, get array: ["", "123456]Ahmed"]
        String[] firstSplit = code.split("\\[");
        if (firstSplit.length > 1) {
            // Split the second part by ], get array: ["123456", "Ahmed"]
            String[] secondSplit = firstSplit[1].split("\\]");
            if (secondSplit.length > 0) {
                System.out.println(secondSplit[0]); // Output: 123456
            }
        }
    }
}

This is a bit clunky compared to the first two methods, but it works if you specifically want to use split.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:51:50