简体   繁体   中英

Java String split() method returns unexpected length of string array

String source = "s5 g900 sued_p033178672__.____ ____.__4.5cm"; // __ __ is not a delimiter 

String deli = "__.__"; // this is my separator string to split target

String[] splittedString = source.split(deli, -1);

splittedString.length; // I expected 3 but was 4

what should I do to split target string properly?

String.split() takes a regular expression as its input. Therefore, . matches any characters, so "__ __" is treated as a delimiter as well.

To make it matches only "__.__" , you need to escape the special character . , ie,

String deli = "__\\.__";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM