我在字符串中获取用户输入,我需要验证它是否采用这种格式"操作数空间操作符空间操作数"或" 2 + 5 * 7 ^ 2"。这是在java中。我研究了几个小时,并尝试正则表达式和循环。我只是无法弄清楚如何验证字符串。下面是我尝试过的一些代码。在这个例子中,我将字符串转换为字符。
for(int i = 0; i < s.length(); i++){
char x = s.charAt(i);
if(!(Character.isDigit(x) || x == '/' || x == '*' ||
x == '+'|| x== '-' || x=='^' || x == '\n'))
throw new InValidCharacterExpression("Invalid expression. Please try again.");
}
}
答案 0 :(得分:0)
如何搜索+ + *之类的运算符然后在运算符之前将字符串拆分为两部分,然后在每个部分中计算空间量,然后修剪结果并将其转换为数字
答案 1 :(得分:0)
我不确定你要找的是什么表达式,但这是一个开头(使用RegEx)
public class ValidateExp {
public static boolean validate(String s) {
Pattern p = Pattern.compile("^(-? ?\\d*[\\.,]?\\d+ ?[\\/\\+\\-\\*\\-\\^])+(-? ?\\d*[\\.,]?\\d+)$");
Matcher m = p.matcher(s);
if(m.find())
return true;
return false;
}
}
是否要将运算符和操作数与空格分开是可选的:
10+10 true
10 + 10 true
10+ 10 true
10 + false
10 *+ 10 false
1 * 1^10 true
1 * 1 ^ 10 true