Splitting a String with the pipe symbol as delimit

2020-04-02 06:25发布

Why is it that in the following, the output is [] and not [1]?

String input="1|2|3";
String[] values= input.split("|");
System.out.println("[" + values[0] + "]");
// Output: []

However, if we change the separator, the output is [1].

String input="1;2;3";
String[] values= input.split(";");
System.out.println("[" + values[0] + "]");
// Output: [1]

6条回答
神经病院院长
2楼-- · 2020-04-02 06:35

Try using \\| instead of | when you split as you need to escape it.

So your code would change to:

String input="1|2|3";
String[] values= input.split("\\|");
System.out.println("[" + values[0] + "]");
查看更多
乱世女痞
3楼-- · 2020-04-02 06:39

Try to escape that character:

String input="1|2|3";
String[] values= input.split("\\|");
System.out.println("[" + values[0] + "]");
查看更多
走好不送
4楼-- · 2020-04-02 06:41

you have to escape the character '|' properly

String input="1|2|3";
        String[] values= input.split("\\|");
        System.out.println("[" + values[0] + "]");
查看更多
等我变得足够好
5楼-- · 2020-04-02 06:44

The pipe character is the equivalent to the logical or in a regex. If you really want to use the pipe character as separator, you need to escape it with a \ as in

String[] values= input.split("\|");

查看更多
成全新的幸福
6楼-- · 2020-04-02 06:47

Because the | has special meaning in regular expressions. You need to escape it like this: \| and in Java you also have to escape the backslash as well so you end up with \\|

The pipe character is a disjunction operator which means that it tells the regular expression engine to choose either pattern on the left and right of it. In your case those where empty strings which match anything.

查看更多
Bombasti
7楼-- · 2020-04-02 06:59

The split method receives a regex as a parameter. The pipe is a reserved character with its own purpose (it means or).

You can either escape it ("\\|") or, if you're in Java 1.5+ you can use Pattern.quote("|") like this:

input.split(Pattern.quote("|"));
查看更多
登录 后发表回答