1

I have a String = A+B+CC-D0. I want to use a regular expression to split it apart to get an array of of the ops {+,+,-}

I have tried the regular expression:

"[^+-]"

But the output gave me a array of { ,+,+, ,+}, why?

    String s1 = "A+B+C-D";
    String s2 = "A0+B0";
    String[] op1 = s1.split([^+-]);
    String[] op2 = s2.split([^+-]);
    for(int i = 0; op1.length; i++){
        System.out.println(op1[i]);
    }

Here's the output:

Output of op1:
""
"+"
"+"
""
"-"

Output of op2:
""
""
"+"
Eagle
  • 339
  • 1
  • 3
  • 14

2 Answers2

2

Replace all the characters other than operators with empty string then split the resultant string according to the boundary which exists between two operators.

String s1 = "A+B+C-D";
String[] op1 = s1.replaceAll("[^+-]","").split("(?<=.)(?=.)");
for(String i: op1){
    System.out.println(i);
}

Output:

+
+
-
  • (?<=.) positive lookbehind which asserts that the match must be preceded by a character.

  • (?=.) Positive lookahead which asserts that the match must be followed by a character.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Maybe you should explain what `split("(?<=.)(?=.)")` is doing exactly. It's quite cryptic. Still +1 because this works quite well. – peter.petrov Mar 01 '15 at 10:08
2

The problem is, you're splitting on single character, that is not + or -. When you split a string - ABC, it will get split 3 times - on A, B and C respectively, and hence you'll get an array - ["", "", "", ""].

To avoid this issue, use quantifier on regex:

String s1 = "A+B+C-D";
String s2 = "A0+B0";
String[] op1 = s1.split("[^+-]+");
String[] op2 = s2.split("[^+-]+");
System.out.println(Arrays.toString(op1));
System.out.println(Arrays.toString(op2));

this is splitting on "[^+-]+".

Now to remove the empty element at the beginning of array, you've to get rid of first delimiter from string, using replaceFirst() may be:

String[] op1 = s1.replaceFirst("[^+-]+", "").split("[^+-]+");
System.out.println(Arrays.toString(op1)); // [+, +, -]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525