java - 管道中的 2 列使用 Java 中的正则表达式分隔 5 列
问题描述
在Java中使用正则表达式从管道分隔7列的3列
例子:
String:
10|name|city||date|0|9013
我只想要城市(3列):
预期输出:
10|name|city
意思是:我想要基于|
使用正则表达式的列数。
谢谢你。
解决方案
我会在 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());
}
推荐阅读
- neo4j - 如果两个节点 Neo4j 之间不存在关系,则返回数据
- python - 可以为 QProgressBar 设置格式以在 pyqt5 中显示带前导零的值吗?
- python - inchstr() 诅咒函数是否在 python 中工作?
- node.js - 从 nodejs 将表单数据发送到 API
- javascript - PWA:使用 service worker 缓存 PHP 文件以供离线使用
- python-3.x - 使用 tk.Scrollbar 更新 tk.canvas 中的图像
- r - 用于分析多个国家和多年数据的回归模型(多元回归中的辛普森悖论)?
- haskell - 为 MultiParamTypeClasses 注释不明确的类型变量
- java - 如何使用 influxdb-java 绑定查询中的参数
- arrays - 根据对象字段减少对象数组