PatternSyntaxException Debug Index Description

PatternSyntaxException reports the failing index and a description, so a regex built from user input can reject bad patterns without guessing.

JavaForm Validation

Code

snippet
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class RegexValidator {

    // 用户输入拼出来的正则可能非法:PatternSyntaxException 自带 debug 用的索引与描述
    static String probe(String rawToken) {
        try {
            Pattern.compile("(" + rawToken + ")");
            return "ok";
        } catch (PatternSyntaxException bad) {
            // getIndex 定位非法字符,getDescription 说明错误类别
            return "invalid at " + bad.getIndex() + ": " + bad.getDescription();
        }
    }

    public static void main(String[] args) {
        System.out.println(probe("alpha"));
        System.out.println(probe("[alpha"));
        System.out.println(probe("*zip"));
    }
}

The flow of the file

PatternSyntaxException Debug Index Description is built around the class RegexValidator and the functions probe and main.

Watch out for

  • The project gains nothing new before this runs.

Using it

The signature at the center: static String probe(String rawToken)

main is the driver: it invokes probe before returning.

Key statements

return "invalid at " + bad.getIndex() + ": " + bad.getDescription();
return "ok";

Interactive Tools for This Topic

FAQ

How do you run PatternSyntaxException Debug Index Description?
The runtime alone is enough: execute the file as a complete program.