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=
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 .
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.
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 "\."
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="]
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With