Splitting a String with the pipe symbol as delimiter

前端 未结 6 1996
情话喂你
情话喂你 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:37

    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.

提交回复
热议问题