Splitting a String with the pipe symbol as delimiter

前端 未结 6 1943
情话喂你
情话喂你 2021-01-17 10:25

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

String input=\"1|2|3\";
String[] values= input.split(\"|\");
System.         


        
6条回答
  •  野的像风
    2021-01-17 10:29

    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("|"));
    

提交回复
热议问题