问题描述
我试图弄清楚为什么这段代码无法正常工作,因为“ 156 154 152-3 +-”符号应不加任何异常地通过。在这种情况下,也许有更好的方法使用正则表达式吗?当我在不手动处理异常的情况下实际运行解释函数时,结果是正确的,一切都很好。但是对于本练习,需要进行此类异常处理。
这是代码:
public class RegexTest {
public static void main(String[] arg) {
boolean b = check_notation("156 154 152 - 3 + -");
System.out.println(b);
}
public static boolean check_notation(String pol){
pol = pol.trim();
String[] tokens = pol.split("\\s+");
for (String r : tokens) {
if (!(r.matches("-[0-9]*") || r.matches("[0-9]*") || r == "/" || r == "*" || r == "-" || r == "+")) {
throw new RuntimeException("There are symbols that are not allowed.");
}
}
return true;
}
}
解决方法
@searchfind ... r.matches()是特殊字符正则表达式检查所必需的。也; \\必须在+和*符号正则表达式之前添加前缀,以避免悬挂的元字符异常。
请在正则表达式条件下使用
if (!(r.matches("-[0-9]*") || r.matches("[0-9]*") || r.matches("/") ||
r.matches("\\*") || r.matches("-") || r.matches("\\+"))) {
throw new RuntimeException("There are symbols that are not allowed.");
}