【问题标题】:Finding where in a String validation failed查找字符串验证失败的位置
【发布时间】: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


【解决方案1】:

要知道验证失败的地方,您需要返回某种形式的对象以及失败的结果。

我建议创建一个新的例外来执行此操作:

public class InvalidInputException extends IllegalArgumentException {

    private int errorIndex;

    public InvalidInputException(String message) {
        super(message);
    }

    public InvalidInputException(String message, int index) { 
         super("Invalid Input at index: " + index + " " + message);
         errorIndex = index;
    }

    public int getErrorIndex() { return errorIndex; }
}

然后,您可以调整验证方法以检测验证失败的位置并将其包含在异常中。例如

throw new InvalidInputException("Missing closing parenthesis", 200);

throw new InvalidInputException("Invalid format");

【讨论】:

  • 我最终自己想出了这样的东西,但你的更干净,谢谢你的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 2012-12-24
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
相关资源
最近更新 更多