【发布时间】:2018-10-02 09:51:01
【问题描述】:
只是想找出最好的方法。
我的输入字符串经过了一些验证方法:
public class Validator {
private static final String VALID_INFIX_REGEX = "^[0-9(]([\\s0-9+*/()-])*[0-9)]$";
public boolean validate(String input) {
return (isValidInfixExpression(input) && hasBalancedParenthesis(input) && checkIfOperatorsAppearConsecutively(input));
}
private boolean isValidInfixExpression(String input) {
final Pattern pattern = Pattern.compile(VALID_INFIX_REGEX);
final Matcher matcher = pattern.matcher(input);
return matcher.matches();
}
private boolean hasBalancedParenthesis(String input) {
String[] tokens = input.split("\\s");
int unclosedParenthesis = 0;
for (int i = 0; i < tokens.length; i++) {
if ("(".equals(tokens[i])) {
unclosedParenthesis++;
} else if (")".equals(tokens[i])) {
unclosedParenthesis--;
}
}
return (unclosedParenthesis == 0);
}
private boolean checkIfOperatorsAppearConsecutively(String input) {
String[] tokens = input.split("\\s");
for (int i = 0; i < tokens.length; i++) {
if (Operator.isOperator(tokens[i])) {
if ("(".equals(tokens[i - 1]) || ")".equals(tokens[i + 1]) || Operator.isOperator(tokens[i + 1])) {
return false;
}
}
}
return true;
}
}
对于用户,我希望能够在字符串中获取验证失败的位置并显示给他们。
我将我的字符串传递给验证,如果失败,我会抛出一个异常:
if (validator.validate(input)) {
// execute
} else {
throw new IllegalArgumentException();
}
为了做到这一点,我最好在实际验证方法中抛出异常还是有更好的方法?
【问题讨论】:
-
“我最好在实际验证中抛出异常” - 是的。您还可以考虑使用字符串验证结果而不是布尔值返回枚举。
标签: java regex validation exception