Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a string by two delimiters?

I know that you can split your string using myString.split("something"). But I do not know how I can split a string by two delimiters.

Example:

mySring = "abc==abc++abc==bc++abc";

I need something like this:

myString.split("==|++")

What is its regularExpression?

like image 483
Bobs Avatar asked Sep 26 '12 08:09

Bobs


2 Answers

Use this :

 myString.split("(==)|(\\+\\+)")
like image 119
Denys Séguret Avatar answered Oct 17 '22 16:10

Denys Séguret


How I would do it if I had to split using two substrings:

String mainString = "This is a dummy string with both_spaces_and_underscores!"
String delimiter1 = " ";
String delimiter2 = "_";
mainString = mainString.replaceAll(delimiter2, delimiter1);
String[] split_string = mainString.split(delimiter1);

Replace all instances of second delimiter with first and split with first.

Note: using replaceAll allows you to use regexp for delimiter2. So, you should actually replace all matches of delimiter2 with some string that matches delimiter1's regexp.

like image 11
Prasanth Avatar answered Oct 17 '22 15:10

Prasanth