我有一个字符串,说1+++-3--+++++2
包含+
和-
符号。
我想要做的是用+
或-
符号表示+
和-
部分。
如果字符串中有奇数个-
符号,我会将其替换为-
,如果是偶数,则替换为+
。我怎么能用正则表达式做到这一点?
例如,我有一个数学表达式,比如1+-+-2-+--+3
。它将被1+2-3
答案 0 :(得分:2)
您可以创建运算符数组并使用newPatient.EmergencyContacts.push({
emerContact_Name: String,
emerContact_Relation: String,
emerContact_Addresses.push({
emerContact_AddressType: String,
emerContact_AddressLine1: String,
emerContact_AddressLine2: String,
emerContact_City: String,
emerContact_Town: String,
emerContact_Village: String,
emerContact_PolicStation: String,
emerContact_District: String,
emerContact_State: String,
emerContact_PinCode: Number
}),
emerContact_ContactInfo.push({
Phone: String,
Email: String
})
});
循环计算一个字符的所有匹配项。例如:
for
在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 = "+";
}
}
中分配修改后的单字符运算符后,编写新表达式应该相对简单。
答案 1 :(得分:1)
基于格式来自该计算器示例的假设。
//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);