简体   繁体   中英

Regex for splitting a string to get operators

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:
""
""
"+"

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.

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)); // [+, +, -]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM