简体   繁体   中英

Java string split gives different outputs on Windows and linux

Please see the below code --

String s11 ="!country=India ";    
String[] ss =s11.split("((?<=[!&|])|(?=[!&|]))");
System.out.println(ss.length);
for(String s :ss) {
  System.out.println(s);
}

On Windows it gives

2
!
country=India 

Whereas with Ubuntu it gives

3

!
country=India 

Why would that be ?

This behavior is not because of different operating systems , but likely different versions of the JVM are used.

This "behavior change" has caused bugs to be filed incorrectly for Java 8.

The documentation has been updated for JDK 8, and is also discussed at length in this question, where split in Java 8 removes empty strings at the start of the result array . This is why the additional empty string before the ! is not created (hence the length of 2 instead 3).

Notice the difference in documentation for the split() method in Java 7 and in Java 8 for the Pattern class, and the string class ( Java 7 , Java 8 ) respectively. See the original question linked for further information on this.

I have also reproduced this issue on Java 7: sun-jdk-1.7.0_10 ( ideone ) and Java 8 sun-jdk-8u25 ( ideone ). See the Java versions here. Java 8's split will provide not add the extra empty string into the array, while Java 7's split will.

This it is not because of the system being Linux or Windows, but rather the JVM version. You can double check your JVM's version with java -version

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