12

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=
blue-sky
  • 51,962
  • 152
  • 427
  • 752

4 Answers4

15

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="]
Steve HHH
  • 12,947
  • 6
  • 68
  • 71
Kyle Falconer
  • 8,302
  • 6
  • 48
  • 68
  • Doesn't work. The `int` parameter is the *limit*. Try `"test1=test1=test1".split("=", 0);` – Michael Yaworski Feb 21 '14 at 02:37
  • @mikeyaworski You apparently didn't read the documentation I linked to, which says: "If n is zero then the pattern will be applied as many times as possible" And *of course* you would change whatever the input string is to match the use case. – Kyle Falconer Feb 21 '14 at 02:41
  • Yes, I apparently did. And as such, I'll answer with a correct answer. – Michael Yaworski Feb 21 '14 at 02:42
3

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]
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
1

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.

roll1987
  • 183
  • 1
  • 7
1

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.

David Ehrmann
  • 7,366
  • 2
  • 31
  • 40