-1

Im trying to split strings like the following :

"a||b && c || true||false" into the following array: {a,||,b,&&,c,||,true,||,false}

Which means that that I want to sepharate each component with the || && delimiters ( they can appear anywhere in the string)

*Note that anything can appear between the || && delimiters. it doesn't really matter to me.

note that white spaces can appear in the string but should be ignored when the string is split into an array.

I didn't manage to find a regex / way to do it, would glad to get help in this subject, thanks!

willkk55
  • 1
  • 1

1 Answers1

1

I think you cann't spit it with one regex because in your input 'a||b && c || true||false' is nothing between a and || to split:

  • a||b -> nothing to split with
  • true||false -> nothing to split with

An easy solution is to add a seperator char befor and after the logical operaors:

string.replaceAll(Pattern.quote("||"), ",||,")
                    .replaceAll(Pattern.quote("&&"), ",&&,");

To remove all whitespaces you can replace them with a empty String:

string.replaceAll("\\s", "");

You can split your prepared String with your seperator char:

String[] splitted = preparedString.split(",");

Complete solution:

public class Test {

    public static void main(String[] args) throws InterruptedException {

        String string = "a||b && c || true||false";

        String preparedString = string.replaceAll(Pattern.quote("||"), ",||,")
                .replaceAll(Pattern.quote("&&"), ",&&,")
                .replaceAll("\\s", "");

        String[] splitted = preparedString.split(",");

        System.out.println(Arrays.toString(splitted));
    }
}

Output:

[a, ||, b, &&, c, ||, true, ||, false]
CodingSamples
  • 184
  • 1
  • 7