How to split a line based on the first occurrence?

How can I split a string based on the first equal sign "="?

So

test1=test1

should be converted to test1, test1(as an array)

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

But what about the CSV string

test1=test1=
+4
source share
4 answers

You can use the second parameter splitas shown in the Java doc

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

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

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

"test1=test1=test1=".split("=", 2);    // ["test1","test1=test1="]
+4
source

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

string.split("=", 2);

2 , 2-1 = 1 , , 2.

+1

Matcher, String.split().

Pattern p = Pattern.compile("([^=]*)=(.*)");
Matcher m = p.matcher("x=y=z"); 
if (m.matches()) { 
    System.out.println(m.group(1));
    System.out.println(m.group(2));
}

, , .

split, s.split("=(?!.*=)"), , , .

+1

Docs, .split(String regex, int limit), : ( ). , int 2 - .

String s = "test1=test2=test3";

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

String s = "test1=test2=";

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

String s = "test1=test2";

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

Source: https://habr.com/ru/post/1528016/


All Articles