split string only on first instance - java split string only on first instance - java java java

split string only on first instance - java


string.split("=", 2);

As String.split(java.lang.String regex, int limit) explains:

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

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.

The string boo:and:foo, for example, yields the following results with these parameters:

Regex Limit    Result:     2        { "boo", "and:foo" }:     5        { "boo", "and", "foo" }:    -2        { "boo", "and", "foo" }o     5        { "b", "", ":and:f", "", "" }o    -2        { "b", "", ":and:f", "", "" }o     0        { "b", "", ":and:f" }


Yes you can, just pass the integer param to the split method

String stSplit = "apple=fruit table price=5"stSplit.split("=", 2);

Here is a java doc reference : String#split(java.lang.String, int)


As many other answers suggest the limit approach, This can be another way

You can use the indexOf method on String which will returns the first Occurance of the given character, Using that index you can get the desired output

String target = "apple=fruit table price=5" ;int x= target.indexOf("=");System.out.println(target.substring(x+1));