Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split by first found String in Java

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)"] 
like image 503
Max_Salah Avatar asked Mar 26 '12 14:03

Max_Salah


People also ask

How do you split a string on first occurrence?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

What does .split do in Java?

Java split() function is used to splitting the string into the string array based on the regular expression or the given delimiter. The resultant object is an array contains the split strings. In the resultant returned array, we can pass the limit to the number of elements.


2 Answers

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.

like image 198
ruakh Avatar answered Sep 21 '22 13:09

ruakh


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

See javadoc for more info

EDIT: Escaped bracket, as per @Pedro's comment below.

like image 30
KingCronus Avatar answered Sep 21 '22 13:09

KingCronus