简体   繁体   English

如何在运算符上将数学表达式拆分为分隔符,同时将它们保留在结果中?

[英]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 

and get a , b , c , d , e seperately(as array of strings) as well as = , - , * , d , / (also an array of operators) separately. 并分别得到abcde (作为字符串数组)以及=-*d/ (也是一组运算符)。 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? 怎么解决?

1st problem: - 第一个问题: -

Multiple declaration of String myString; String myString;多重声明String myString;

2nd problem: - 第二个问题: -

String initialized incorrectly. 字符串初始化不正确。 Double quotes missing at the ends. 两端缺少双引号。 Remove bracket and brace from the ends. 从两端卸下支架和支架。

String myString = "a+b-c*d/e";

3rd problem: - 第3个问题: -

String array initialized with an String object, rather than an array object. String数组使用String对象而不是数组对象初始化。

String[] result=new String();  // Should be `new String[size]`

In fact, you don't need to initialize your array before hand. 实际上,您不需要事先初始化数组。

4th problem: - 第四个问题: -

String.split takes a Regular Expression as argument, you have passed an array. String.split将Regular Expression作为参数,您已经传递了一个数组。 Will not work. 不管用。

Use: - 采用: -

String[] result = myString.split("[-+*/]");

to split on all the operators. 拆分所有运营商。


And regarding your this statement: - 关于你的这句话: -

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 . 并且d不是operator Please see if you want to edit it. 请查看是否要编辑它。

UPDATE : - 更新: -

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("(?=[-+*/])")));

OUTPUT : - 输出: -

[a, +, b, -, c, *, d, /, e]
[a+, b-, c*, d/, e]
[a, +b, -c, *d, /e]

(?<=...) means look-behind assertion , and (?=...) means look-ahead assertion . (?<=...)表示后look-behind assertion(?=...)表示look-ahead assertion

Besides the split approach, you could also use java.util.StringTokenizer : 除了split方法,您还可以使用java.util.StringTokenizer

 String myString = "a+b-c*d/e";

 List<String> operatorList = new ArrayList<String>();
 List<String> operandList = new ArrayList<String>();
 StringTokenizer st = new StringTokenizer(myString, "+-*/", true);
 while (st.hasMoreTokens()) {
    String token = st.nextToken();

    if ("+-/*".contains(token)) {
       operatorList.add(token);
    } else {
       operandList.add(token);
    }
 }

 System.out.println("Operators:" + operatorList);
 System.out.println("Operands:" + operandList);

Result: 结果:

Operators:[+, -, *, /]
Operands:[a, b, c, d, e]

Just to get the a/b/c/d/e: 只是为了获得a / b / c / d / e:

String myString = "a+b-c*d/e";
String[] result=myString.split("[-+*/]");

In a more readable form: 以更易读的形式:

String myString = "a+b-c*d/e";
String[] result2=myString.split("["+Pattern.quote("+-*/")+"]");

To get the +-*/: 获得+ - * /:

ArrayList<Character> list = new ArrayList<Character>();
for (char c:myString.toCharArray())
{
   if ("+-*/".contains(""+c)) list.add(c);
}
System.out.println(list);

Edit: removed unneeded escape characters. 编辑:删除不需要的转义字符。

As far as I know you cannot do what you are after right out of the box. 开箱即用,据我所知,你不能做你想做的事。 The split(String regex) does not take an entire array (unlike C#), just a string representing a valid regular expression. split(String regex)不占用整个数组(与C#不同),只是表示有效正则表达式的字符串。

What you could do would be to define a Set which contains your operators and 2 ArrayLists . 你可以做的是定义一个包含你的运算符和2个ArrayListsSet Once you have that, you iterate over your string, check if the set contains that given character (thus determining if it is an operator or not). 一旦你有了,你迭代你的字符串,检查集合是否包含给定的字符(从而确定它是否是一个运算符)。 If it is, then, you put it in one list, if not, you put it in the other. 如果是,那么,你把它放在一个列表中,如果没有,你把它放在另一个列表中。

Finally, you can then use toArray(new String\\[arraySize\\]) to get back your ArrayLists as String arrays. 最后,您可以使用toArray(new String\\[arraySize\\])ArrayLists作为String数组返回。

I think what you want to do, is more like a parser, rather than a tokenizer. 我想你想要做的,更像是一个解析器,而不是一个tokenizer。

With a string tokenizer, you usually have a long string (ie "parameter1;parameter2;parameter3") with several elements concatenated, and using a "token" to separate these elements. 使用字符串标记生成器,通常会有一个长字符串(即“parameter1; parameter2; parameter3”),其中连接了多个元素,并使用“标记”来分隔这些元素。 With function "String.split", you are basically saying: "Ok, give all elements from this string, but taking into account that character ';' 使用函数“String.split”,你基本上会说:“好的,给出这个字符串中的所有元素,但要考虑到这个字符';' separates different elements". 分离不同的元素“。 And then you get "parameter1", "parameter2", "parameter3". 然后你得到“parameter1”,“parameter2”,“parameter3”。 You do not care about separators. 你不关心分隔符。

But in a mathematical expression like yours: "a+bc*d/e", you want to get all the individual elements (operands and operators). 但是在像你这样的数学表达式中:“a + bc * d / e”,你想获得所有单独的元素(操作数和运算符)。 Here there are no explicit separators, and the order is also important for you. 这里没有明确的分隔符,顺序对您也很重要。 I would use a parser library and write a small grammar instead. 我会使用解析器库并编写一个小语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将运算符上的逻辑表达式拆分为分隔符,同时将它们保留在结果中? - How to Split a logical expression on operators as delimiters, while keeping them in the result? 如何在Java中保留分隔符的同时在不同的分隔符之间拆分文本? - How to split text between different delimiters while keeping delimiters in Java? 如何在数学运算符上将字符串拆分为定界符,但在引号内转义运算符(在Java中)? - How to Split a String on mathematical operators as delimiters but escape operators inside quotes (in java)? 正则表达式拆分与分隔符同时保持分隔符 - Regex Split with Delimiters while keeping delimiters 如何在保留不同分隔符计数的同时拆分字符串? - How to split a string while keeping a count of the different delimiters? 如何拆分字符串,只保留某些分隔符? - How to split a string, keeping only certain delimiters? 如何拆分 java 中组件的数学表达式? - How to split mathematical expression on components in java? 拆分数学表达式 - Split a mathematical expression 如何拆分字符串(基于各种分隔符)但不保留空格? - How to split a string (based on a variety of delimiters) but without keeping whitespace? 使用Java处理负数时拆分数学表达式 - Split a mathematical expression while handling negative numbers with Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM