Split by first found String in Java

Max_Salah picture Max_Salah · Mar 26, 2012 · Viewed 19.7k times · Source

is ist possible to tell String.split("(") function that it has to split only by the first found string "("?

Example:

String test = "A*B(A+B)+A*(A+B)";
test.split("(") should result to ["A*B" ,"A+B)+A*(A+B)"]
test.split(")") should result to ["A*B(A+B" ,"+A*(A+B)"]

Answer

ruakh picture ruakh · Mar 26, 2012

Yes, absolutely:

test.split("\\(", 2);

As the documentation for String.split(String,int) explains:

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.