Home > Software design >  String Split in Java Giving Unexpected Results
String Split in Java Giving Unexpected Results

Time:04-15

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?

CodePudding user response:

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]
  • Related