4

Could you please let me know whether we have any StringUtils function to split based on comma and space. Basically i am wondering whether we have any function which will split based on two delimiters. I have written custom function to do the same, but just checking whether we have any good function in any utils package.

The way I have done is to replace first delimiter with second one and then split based on second delimiter.

Adam
  • 727
  • 4
  • 11
  • 21

2 Answers2

5

You can use this version of split, for example

String[] strings = StringUtils.split("some,random words", ", ");

or the built-in split method (as per my comment)

String[] strings = "some,random words".split("[, ]")?
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Be aware that these methods don't behave always the same. I've noticed that the built-in split method doesn't return a (leading) empty element while StringUtils.split does. Both don't return a trailing empty element. – pi3 Sep 18 '16 at 13:47
1

String.split() accepts a regex expression, so you can use:

"test,string split".split("[, ]")

EDIT: Just noticed Reimeus already mentioned this.

shmosel
  • 49,289
  • 6
  • 73
  • 138