Oscar Orcas
Oscar Orcas

Reputation: 127

Splitting a string in Java using multiple delimiters

I have a string like

String myString = "hello world~~hello~~world"

I am using the split method like this

String[] temp = myString.split("~|~~|~~~");

I want the array temp to contain only the strings separated by ~, ~~ or ~~~.

However, the temp array thus created has length 5, the 2 additional 'strings' being empty strings.

I want it to ONLY contain my non-empty string. Please help. Thank you!

Upvotes: 1

Views: 2112

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213203

You should use quantifier with your character:

String[] temp = myString.split("~+");

String#split() takes a regex. ~+ will match 1 or more ~, so it will split on ~, or ~~, or ~~~, and so on.

Also, if you just want to split on ~, ~~, or ~~~, then you can limit the repetition by using {m,n} quantifier, which matches a pattern from m to n times:

String[] temp = myString.split("~{1,3}");

When you split it the way you are doing, it will split a~~b twice on ~, and thus the middle element will be an empty string.

You could also have solved the problem by reversing the order of your delimiter like this:

String[] temp = myString.split("~~~|~~|~");   

That will first try to split on ~~, before splitting on ~ and will work fine. But you should use the first approach.

Upvotes: 8

Vimal Bera
Vimal Bera

Reputation: 10497

Try This :

myString.split("~~~|~~|~");

It will definitely works. In your code, what actually happens that when ~ occurs for the first time,it count as a first separator and split the string from that point. So it doesn't get ~~ or ~~~ anywhere in your string though it is there. Like :

[hello world]~[]~[hello]~[]~[world]

Square brackets are split-ed in to 5 different string values.

Upvotes: 3

Moritz Petersen
Moritz Petersen

Reputation: 13047

Just turn the pattern around:

    String myString = "hello world~~hello~~world";
    String[] temp = myString.split("~~~|~~|~");

Upvotes: 4

Related Questions