javasplitqregularexpression

String split if the first character is minus then tread it as a negative sign


- sign can be treated as operator or negative sign. If - is located in the start, it shall be treated as the negative sign and a subtraction whiting the string. This is only apply to - sign while the + will be always the add sign. How can I achieve this?

input:

-23-23+4=F1Qa;
+23-23+4=F1Qa;

output:

["-23","-","23","+","4","=","F","1","Q","a",";"]
["+", "23","-","23","+","4","=","F","1","Q","a",";"]

This is what I've tried so far

String regx = (?:# .*? #:?)|(?!^)(?=\\D)|(?<=\\D)(?=\\d-)
String[] splits = inputString.split(regx);

Solution

  • You can use the regex, ^-\d+|\d+|\D which means either negative integer in the beginning (i.e. ^-\d+) or digits (i.e. \d+) or a non-digit (\D).

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
    
        public static void main(String[] args) {
            String str = "-23-23+4=F1Qa;";
            Pattern pattern = Pattern.compile("^-\\d+|\\d+|\\D");
            Matcher matcher = pattern.matcher(str);
            while (matcher.find()) {
                System.out.println(matcher.group());
            }
        }
    }
    

    Output:

    -23
    -
    23
    +
    4
    =
    F
    1
    Q
    a
    ;
    

    Another test:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
    
        public static void main(String[] args) {
            String str = "+23-23+4=F1Qa;";
            Pattern pattern = Pattern.compile("^-\\d+|\\d+|\\D");
            Matcher matcher = pattern.matcher(str);
            while (matcher.find()) {
                System.out.println(matcher.group());
            }
        }
    }
    

    Output:

    +
    23
    -
    23
    +
    4
    =
    F
    1
    Q
    a
    ;