使用正则表达式从操作数中拆分和提取运算符

split and extract Operator from Operand with Regex

我有一个包含运算符和操作数的方程式。 我想拆分它并将运算符和操作数提取到一个字符串数组中,如下所示:

4+3 -2 + 1* 5 -2

4,+,-,2,+,1,*,5,-,2

有人对此有建议的正则表达式模式吗?

您要执行的操作称为 tokenization. You shouldn't need a RegEx for this. You should be able to just use a StringTokenizer. The answers on this other SO post should suit your needs: String Tokenizer in Java

更新

尽管最初的建议应该符合您的需要,但 StringTokenizer class 似乎已接近弃用。

来自 javadocs:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

无论如何,它,如果您想使用它,则可以选择。

这里有一个使用正则表达式的方法,没有用过这些,所以可能会有所改进。

Pattern pattern = Pattern.compile("[0-9]+|(\+|-|\*)");
Matcher matcher = pattern.matcher("4+3 -2 + 1* 5 -2");
List<String> parts = new ArrayList<>();
while (matcher.find()) {
    parts.add(matcher.group());
}
String[] array = parts.toArray(new String[parts.size()]);
System.out.println(Arrays.toString(array));

输出:

[4, +, 3, -, 2, +, 1, *, 5, -, 2]