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

Java实现字符串内相同行号对应座位短语分组合并的方法

可以通过正则表达式实现该需求,也可以用拆分遍历的方式完成,两种方案如下:

方案1:正则表达式实现

核心思路是匹配重复出现的相同行号Row声明,只保留首个有效声明,全局替换即可得到结果。

  • 匹配正则:(Row:?\s*\d+)(,.*?)(?:,\s*\1)+
  • 替换规则:$1$2

Java语言实现示例:

String in = "Row: 1, Seat: 1, Row: 1, Seat: 2, Row: 1, Seat: 3, Row 4: Seat 10, Row 5: Seat 8, Row 5: Seat 9";
String out = in.replaceAll("(Row:?\\s*\\d+)(,.*?)(?:,\\s*\\1)+", "$1$2");
System.out.println(out);
// 输出结果:Row: 1, Seat: 1, Seat: 2, Seat: 3, Row 4: Seat 10, Row 5: Seat 8, Seat 9

方案2:拆分遍历实现(兼容性更强)

如果输入字符串格式存在波动,拆分遍历的方式容错性更高,不会出现正则匹配偏差:

String in = "Row: 1, Seat: 1, Row: 1, Seat: 2, Row: 1, Seat: 3, Row 4: Seat 10, Row 5: Seat 8, Row 5: Seat 9";
String[] parts = in.split(", ");
List<String> resultList = new ArrayList<>();
String preRow = null;
for (String item : parts) {
    // 遇到重复的Row声明直接跳过
    if (item.startsWith("Row")) {
        if (item.equals(preRow)) {
            continue;
        }
        preRow = item;
    }
    resultList.add(item);
}
String out = String.join(", ", resultList);

内容的提问来源于stack exchange,提问作者Razvie-arr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 21:36:04