How to check if a given Regex is valid?

前端 未结 7 2235
时光取名叫无心
时光取名叫无心 2020-12-05 02:08

I have a little program allowing users to type-in some regular expressions. afterwards I like to check if this input is a valid regex or not.

I\'m w

7条回答
  •  臣服心动
    2020-12-05 02:18

    Here is an example.

    import java.util.regex.Pattern;
    import java.util.regex.PatternSyntaxException;
    
    public class RegexTester {
        public static void main(String[] arguments) {
            String userInputPattern = arguments[0];
            try {
                Pattern.compile(userInputPattern);
            } catch (PatternSyntaxException exception) {
                System.err.println(exception.getDescription());
                System.exit(1);
            }
            System.out.println("Syntax is ok.");
        }
    }
    

    java RegexTester "(capture" then outputs "Unclosed group", for example.

提交回复
热议问题