How Can I Split a String by Two Delimiters?

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?

3

4 Answers

Use this :

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

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.

You can use this

        mySring = "abc==abc++abc==bc++abc";
        String[] splitString = myString.split("\\W+");

Regular expression \W+ ---> it will split the string based upon non-word character.

Try this

String str = "aa==bb++cc";
String[] split = str.split("={2}|\\+{2}");
System.out.println(Arrays.toString(split));

The answer is an array of

[aa, bb, cc]

The {2} matches two characters of the proceding character. That is either = or + (escaped) The | matches either side

I am escaping the \ in java so the regex is actually ={2}|\+{2}

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.