如何将运算符上的数学表达式拆分为分隔符,同时将它们保留在结果中? [英] How to Split a mathematical expression on operators as delimiters, while keeping them in the result?
问题描述
我需要拆分一个表达式,如
I need to split an expression like
a+b-c*d/e
并获得 a
, b
, c
, d
, e
单独(作为数组) (字符串)以及 =
, -
, *
, d
, /
(也是一组运算符)分开。我尝试过:
and get a
, b
, c
, d
, e
seperately(as array of strings) as well as =
,-
,*
,d
,/
(also an array of operators) separately. I have tried like:
String myString;
String myString={"a+b-c*d/e");
String[] result=new String();
String[] separator=new String[]{"+","-","/","*"};
result=myString.split(separator);
但是,它显示错误。如何解决?
But, it shows an error. How to solve it?
推荐答案
第一个问题: -
多个声明字符串myString;
第二个问题: -
字符串初始化不正确。两端缺少双引号。从两端移除支架和支架。
String initialized incorrectly. Double quotes missing at the ends. Remove bracket and brace from the ends.
String myString = "a+b-c*d/e";
第3个问题: -
使用String对象而不是数组对象初始化String数组。
String array initialized with an String object, rather than an array object.
String[] result=new String(); // Should be `new String[size]`
实际上,你不需要初始化你手上的阵列。
In fact, you don't need to initialize your array before hand.
第4个问题: -
String.split
将Regular Expression作为参数,您已经传递了一个数组。无效。
String.split
takes a Regular Expression as argument, you have passed an array. Will not work.
使用: -
String[] result = myString.split("[-+*/]");
将拆分所有运营商。
关于你的这句话: -
And regarding your this statement: -
以及
=, - ,*,d,/
(也是一组运营商)分开。
as well as
=, -, *, d, /
(also an array of operators) separately.
我不喜欢不明白你想要什么。您的示例字符串不包含 =
。并且 d
不是运算符
。请查看是否要修改。
I don't understand what you want here. Your sample string does not contains =
. And d
is not an operator
. Please see if you want to edit it.
更新: -
如果你的意思是保持运算符在你的数组中,你可以使用这个正则表达式: -
If you mean to keep the operators as well in your array, you can use this regex: -
String myString= "a+b-c*d/e";
String[] result = myString.split("(?<=[-+*/])|(?=[-+*/])");
System.out.println(Arrays.toString(result));
/*** Just to see, what the two parts in the above regex print separately ***/
System.out.println(Arrays.toString(myString.split("(?<=[-+*/])")));
System.out.println(Arrays.toString(myString.split("(?=[-+*/])")));
输出: -
[a, +, b, -, c, *, d, /, e]
[a+, b-, c*, d/, e]
[a, +b, -c, *d, /e]
(?< = ...)
表示后置断言
和(?=。 ..)
表示预见断言
。
这篇关于如何将运算符上的数学表达式拆分为分隔符,同时将它们保留在结果中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!