split failure analysis

String oneTextValue = "1223)234";
String[] chunks = oneTextValue.split("\\)");

String oneTextValue2 = "1223)234)";
String[] chunks2 = oneTextValue2.split("\\)");

String oneTextValue3 = "1223234";
String[] chunks3 = oneTextValue3.split("\\)");

String oneTextValue4 = ")1223234";
String[] chunks4 = oneTextValue4.split("\\)");

![Insert picture description here](https://img-blog.csdnimg.cn/d4604edd6c0140cfbaa3cd575c3189bd.png) **Phenomenon**

The problem that the empty string at the end is discarded
In the second example, the result is not {"1223", "234", ""}, but {"1223", "234"}
to avoid discarding the empty string at the end

     
     
      
      
String oneTextValue2 = "1223)234)";
String[] chunks2 = oneTextValue2.split("\\)", -1);

Result:
insert image description here
Escape character
1. If "." is used as a separator, it must be written as follows: String.split("\."), so that it can be separated correctly, and String.split(".");
2. If "|" is used as a separator, it must be written as follows: String.split("\|"), so that it can be separated correctly. You cannot use String.split("|"); "." and " |" are escape characters, you must add "\";

multiple separators

  1. If there are multiple separators in a string, you can use "|" as a hyphen
     
     
      
      
String oneTextValue = "12(23)234";
String[] chunks = oneTextValue.split("\\(|\\)");

result
{"12", "23", "234"}

Guess you like

Origin blog.csdn.net/qq_38747892/article/details/131042035