简体   繁体   中英

String Split in Java Giving Unexpected Results

I have a series of strings with the following format: "animal || type || area ||".

In Java, I'm trying to split the string so I can just the first part. Everything I have read online says to split the string:

String animalString = "animal || type || area"
String animalArray[] = animalString.split("||")

System.out.println("result = " + Arrays.toString(animalArray));

However, when I split the string it doesn't merely split based on the '||'division but instead splits every letter:

result = [a, n, i, m, a, l,  , |, |,  , t, y, p, e,  , |, |,  , a, r, e, a,  , |, |]

When I add a delimiter to the split method, it delimits the first part of the string, so that is not effective.

How can I split a string that has the above format so I can get the three words themselves in an array and not just the letters?

You need to double escape them. Once for the String and once for the regex . \\ escapes the slash so it can be passed on to the regex as \| which escapes the | .

The \\s* allows for 0 or more white spaces before and after the ||

String animalString = "animal || type || area";
String animalArray[] = animalString.split("\\s*\\|\\|\\s*");

System.out.println("result = " + Arrays.toString(animalArray));

prints

result = [animal, type, area]

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