2

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

输入:

-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);
4

1 回答 1

1

您可以使用正则表达式,^-\d+|\d+|\D这表示开头的负整数 (ie ^-\d+) 或数字 (ie \d+) 或非数字 ( \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
;
于 2020-10-18T21:46:51.060 回答