blue-sky
blue-sky

Reputation: 53816

How to split a String based on first occurence?

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=

Upvotes: 12

Views: 15766

Answers (4)

David Ehrmann
David Ehrmann

Reputation: 7576

This is a better job for a Matcher than String.split(). Try

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));
}

If grabs all it can up to the first equal sign, then everything after that.

If you insist on split, s.split("=(?!.*=)"), but please don't.

Upvotes: 1

Kyle Falconer
Kyle Falconer

Reputation: 8490

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="]

Upvotes: 16

Michael Yaworski
Michael Yaworski

Reputation: 13483

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]

Upvotes: 3

roll1987
roll1987

Reputation: 183

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.

Upvotes: 1

Related Questions