user2365199
user2365199

Reputation: 29

Split issues with string in java

I found that split regex in java is working as greedy

String str = ";;;";
System.out.println(str.split(";").length);

output - 0 (wrong)

expected - 4

String str = ";;;a";
System.out.println(str.split(";").length);

output - 4

I tried to modified the regex and make it lazy using regex as ;+? but got output as 0.

Any idea how to make regex as greedy for split here will be much appreciated.

Thanks in advance

Upvotes: 0

Views: 221

Answers (4)

Bohemian
Bohemian

Reputation: 425348

It has nothing to do with greediness. It has to do with the split() implementation.

By default, all trailing blank matches are ignored. Since you only have blank matches, all matches are discarded.

To override this behaviour of ignoring trailing blanks, invoke split with a second parameter of -1;

str.split(";", -1);

This second parameter n is the limit and the javadoc says:

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

See the javadoc for split() more detail.

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136122

String.split(String s) API says that trailing empty strings are not included in the resulting array. If you want them to be included try with unlimited limit

    String str = ";;;";
    System.out.println(str.split(";", Integer.MAX_VALUE).length);

Upvotes: 0

Rahul
Rahul

Reputation: 45080

You need to specify the limit, to achieve what you want.

str.split(";", -1); // -1 is the limit, which will make the split method greedy as you want.

Non-Positive limit means that the pattern will be applied as many times as possible!

Therefore System.out.println(str.split(";").length); will now print 4, as required.

Have a look at the docs for more detailed info.

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 122026

Try

 String str = ";;;"; 
 System.out.println(str.split(";",-1).length); //LIMIT missed 

Upvotes: 0

Related Questions