Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string only on first instance - java

Tags:

java

string

split

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

like image 637
dracula Avatar asked Aug 27 '13 10:08

dracula


People also ask

How do you split a string only on the first instance of specified character?

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.

How do I split a string with first space?

Using the split() Method For example, if we put the limit as n (n >0), it means that the pattern will be applied at most n-1 times. Here, we'll be using space (” “) as a regular expression to split the String on the first occurrence of space.

How do you split on the first occurrence?

Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .


1 Answers

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" } 
like image 150
Zaheer Ahmed Avatar answered Sep 23 '22 13:09

Zaheer Ahmed