首页 > 解决方案 > 管道中的 2 列使用 Java 中的正则表达式分隔 5 列

问题描述

在Java中使用正则表达式从管道分隔7列的3列

例子:

String:
10|name|city||date|0|9013

我只想要城市(3列):

预期输出:

10|name|city

意思是:我想要基于|使用正则表达式的列数。

谢谢你。

标签: javaregex

解决方案


我会在 split 方法中使用简单的正则表达式模式。可能有一种更优雅的方式来处理生成的字符串中的管道,但这应该会给你一个想法,祝​​你好运!

  public static void main(String[] args) {
     String str = "10|name|city||date|0|9013";
     // split the string whenever we see a pipe
     String[] arrOfStr = str.split("\\|");
     StringBuilder sb = new StringBuilder();
     // loop through the array we generated and format our output
     // we only want the first three elements so loop accordingly
     for (int i = 0; i < 3; i++) {
       sb.append(arrOfStr[i]+"|");
     }
     // remove the trailing pipe
     sb.setLength(sb.length() - 1);
     System.out.println(sb.toString());
  }

推荐阅读