java 用“|”分割Java字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16311651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:36:58  来源:igfitidea点击:

Java String Split by "|"

javastringstring-split

提问by Vijay

I am trying to parse some data using Java which is separated by '|' sequence. Below is an example of the data.

我正在尝试使用以“|”分隔的 Java 解析一些数据 顺序。下面是一个数据示例。

String s = "111206|00:00:00|2|64104|58041";
String [] temp = s.split("|");
for(String p: temp)
System.out.println(p);

But instead of splitting at '|' it separates every character separately. Here is the output I get for the above code.

但不是在“|”处拆分 它将每个字符分开。这是我为上述代码得到的输出。

 1
 1
 1
 2
 0
 6
 |
 0
 0
 :
 0
 0
 :
 0
 0
 |
 2
 |
 6
 4
 1
 0
 4
 |
 5
 8
 0
 4
 1

I found a turn around by replacing the '|' by ',' in the line, but the patch of code is going to run many times and I want to optimize it.

我通过替换“|”找到了转机 通过 ',' 行,但是代码补丁将运行多次,我想对其进行优化。

 String s = "111206|00:00:00|2|64104|58041";
 s = s.replace('|', ',');

I just want to know what the problem is with '|' ??

我只想知道'|'有什么问题 ??

回答by Doorknob

You must use:

您必须使用:

String [] temp = s.split("\|");

This is because the splitmethod takes a regular expression, and |is one of the special characters. It means 'or'. That means you are splitting by '' or '', which is just ''. Therefore it will split between every character.

这是因为该split方法采用正则表达式,并且|是特殊字符之一。它的意思是“或”。这意味着您正在拆分'' or '',这就是''。因此它将在每个字符之间拆分。

You need two slashes because the first one is for escaping the actual \in the string, since \is Java's escape character in a string. Java understands the string like "\|", and the regex then understands it like "|".

你需要两条斜线,因为第一个是转义实际\的字符串,因为\是在一个字符串Java的转义字符。Java 理解字符串像“ \|”,然后正则表达式理解它像“ |”。