Java如何按指定条件拆分字符串以获取预期输出结果
问题分析
你的原有代码存在两处明显错误:
- 变量声明顺序异常:你在调用
s.split()方法后才声明初始化字符串s,代码会直接编译报错,必须先完成字符串变量的定义赋值,再调用对应的实例方法。 - 拆分规则不匹配需求:直接按单个空格全量拆分,会把目标字符串拆为
Apple、not、in、Vegetable,Object,Item四个元素,和预期的3个结果不符。
实现代码
你可以通过二次拆分的方式实现需求,也可以用正则分组捕获的方式完成匹配:
方案1:二次拆分实现
public class SplitTest { public static void main(String[] args) { String s = "Apple not in Vegetable,Object,Item"; // 第一次拆分:匹配最后一个空格,拆为前半部分和末尾逗号分隔的内容 String[] firstSplit = s.split(" (?=\\S*$)", 2); // 第二次拆分:把前半部分按第一个空格拆为首个单词和中间内容 String[] secondSplit = firstSplit[0].split(" ", 2); // 组装最终结果 String[] result = {secondSplit[0], secondSplit[1], firstSplit[1]}; // 输出验证 for (String item : result) { System.out.println(item); } } }
方案2:正则分组捕获实现
如果你的拆分规则固定为「首个单词+中间空格分隔的文本+末尾逗号分隔的无空格文本」,可以直接用正则分组匹配,逻辑更清晰:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class SplitTest { public static void main(String[] args) { String s = "Apple not in Vegetable,Object,Item"; Pattern pattern = Pattern.compile("(\\w+) ([\\w ]+) ([\\w,]+)"); Matcher matcher = pattern.matcher(s); if (matcher.matches()) { System.out.println(matcher.group(1)); System.out.println(matcher.group(2)); System.out.println(matcher.group(3)); } } }
两种方案的输出结果均为:
Apple not in Vegetable,Object,Item
内容的提问来源于stack exchange,提问作者Juhi Sehgal
相关产品推荐
相关产品推荐

