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:
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 } } }
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 } } }
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

