javastringsplit

split string only on first instance - java


I want to split a string by '=' charecter. But I want it to split on first instance only. How can I do that ? Here is a JavaScript example for '_' char but it doesn't work for me split string only on first instance of specified character

Example :

apple=fruit table price=5

When I try String.split('='); it gives

[apple],[fruit table price],[5]

But I need

[apple],[fruit table price=5]

Thanks


Solution

  • string.split("=", limit=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" }