Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a String based on first occurence?

Tags:

java

regex

How can I split a String based on the first equals sign "="?

So

test1=test1

should be transformed into test1, test1 (as an array)

"test1=test1".split("=") works fine in this example.

But what about the CSV string

test1=test1=
like image 299
blue-sky Avatar asked Feb 21 '14 02:02

blue-sky


People also ask

How do you split a string with the first occurrence of a character in python?

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 .

How do I split a string with first space?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

How do you split a string by period?

The split() method of the String class is used to split the given string around matches of the given regular expression. To split a string by dot pass a dot by placing double escape characters as "\."


3 Answers

You can use the second parameter of split as seen in the Java doc

If you want the split to happen as many times as possible, use:

"test1=test1=test1=".split("=", 0);    // ["test1","test1","test1"]

If you want the split to happen just once, use:

"test1=test1=test1=".split("=", 2);    // ["test1","test1=test1="]
like image 67
Kyle Falconer Avatar answered Nov 15 '22 17:11

Kyle Falconer


Try looking at the Docs because there is another .split(String regex, int limit) method that takes in two parameters: the regex and the limit (limiting size of array). So you can apply the int limit to be only 2 - where the array can hold only two elements.

String s = "test1=test2=test3";

System.out.println(Arrays.toString(s.split("=", 2))); // [test1, test2=test3]

Or

String s = "test1=test2=";

System.out.println(Arrays.toString(s.split("=", 2))); // [test1, test2=]

Or

String s = "test1=test2";

System.out.println(Arrays.toString(s.split("=", 2))); // [test1, test2]
like image 23
Michael Yaworski Avatar answered Nov 15 '22 16:11

Michael Yaworski


You can find the index of the first "=" in the string by using the method indexOf(), then use the index to split the string.

Or you can use

string.split("=", 2);

The number 2 here means the pattern will be used at most 2-1=1 time and thus generates an array with length 2.

like image 22
roll1987 Avatar answered Nov 15 '22 16:11

roll1987