如果第一个字符为负号,则字符串拆分,然后将其视为负号

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

- 符号可被视为运算符或负号。如果 - 位于开头,则应将其视为负号和字符串的减法。这仅适用于 - 符号,而 + 始终是加号。我怎样才能做到这一点?

输入:

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

输出:

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

这是我目前尝试过的方法

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

您可以使用正则表达式,^-\d+|\d+|\D 表示开头为负整数(即 ^-\d+)或数字(即 \d+)或 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());
        }
    }
}

输出:

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

另一个测试:

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());
        }
    }
}

输出:

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