[英]Regular Expressions - match a string containing “+” and “-”
I have a string, say 1+++-3--+++++2
that includes +
and -
sign. 我有一个字符串,例如
1+++-3--+++++2
,其中包含+
和-
号。 What I want to do is to represent the +
and -
part with +
or -
sign. 我想做的是用
+
或-
号代表+
和-
部分。 If there are an odd number of -
sign in the string, I will replace it with -
, and +
if that is an even number. 如果字符串中的
-
号有奇数,我将用-
替换,如果是偶数则用+
代替。 How can I do that using regex? 我该如何使用正则表达式呢?
For example, I have a math expression, say 1+-+-2-+--+3
. 例如,我有一个数学表达式,例如
1+-+-2-+--+3
。 It will be replaced by 1+2-3
它将被
1+2-3
替换
You can create an array of the operators and use a for
loop to count all occurrences of one character. 您可以创建一个运算符数组,并使用
for
循环来计数一个字符的所有出现次数。 For example: 例如:
String expression = "1+++-3--+++++2";
String[] str = expression.split("[0-9]+");
for(op : str) {
int count = 0;
for(int i =0; i < str.length(); i++)
if(op.charAt(i) == '-')
count++;
if(count % 2 == 0) {
op = "-";
}
else {
op = "+";
}
}
After assigning the modified one-character operators in str[]
, it should be relatively simple to write the new expression. 在
str[]
分配修改后的单字符运算符后,编写新表达式应该相对简单。
based on the assumption that the format will be from that calculator example. 基于格式将来自该计算器示例的假设。
//assumed format for input: <any number><any number of `-` and/or `+`><any number>
// 1++---+22+--1 will be 1-22+1
String input = "1++---+22+--1";
for (String s : input.split("[^-+]+");) {
s = s.trim();
if (!"".equals(s)) {
String newStr = s.matches("[+]*-([+]*-[+]*-)*[+]*") ? "-" : "+";
input = input.replace(s, newStr);
}
}
System.out.println(input);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.