How to check if a given Regex is valid?

前端 未结 7 2228
时光取名叫无心
时光取名叫无心 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:25

    try this :

    import java.util.Scanner;
    import java.util.regex.*;
    
    public class Solution
    {
          public static void main(String[] args){
          Scanner in = new Scanner(System.in);
          int testCases = Integer.parseInt(in.nextLine());
          while(testCases>0){
            String pattern = in.nextLine();
            if(pattern != null && !pattern.equals("")){
                try{
                    Pattern.compile(pattern);
                    System.out.println("Valid");
                }catch(PatternSyntaxException e){
                    System.out.println("Invalid");
                }
            }
            testCases--;
            //Write your code
         }
      }
     }
    

    use input to test :
    3
    ([A-Z])(.+)
    [AZa-z
    batcatpat(nat

提交回复
热议问题