How to check if a given Regex is valid?

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

    You can just Pattern.compile the regex string and see if it throws PatternSyntaxException.

        String regex = "***";
        PatternSyntaxException exc = null;
        try {
            Pattern.compile(regex);
        } catch (PatternSyntaxException e) {
            exc = e;
        }
        if (exc != null) {
            exc.printStackTrace();
        } else {
            System.out.println("Regex ok!");
        }
    

    This one in particular produces the following output:

    java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
    ***
    ^
    

    Regarding lookbehinds

    Here's a quote from the old trusty regular-expressions.info:

    Important Notes About Lookbehind

    Java takes things a step further by allowing finite repetition. You still cannot use the star or plus, but you can use the question mark and the curly braces with the max parameter specified. Java recognizes the fact that finite repetition can be rewritten as an alternation of strings with different, but fixed lengths.

    I think the phrase contains a typo, and should probably say "different, but finite lengths". In any case, Java does seem to allow alternation of different lengths in lookbehind.

        System.out.println(
            java.util.Arrays.toString(
                "abracadabra".split("(?<=a|ab)")
            )
        ); // prints "[a, b, ra, ca, da, b, ra]"
    

    There's also a bug in which you can actually have an infinite length lookbehind and have it work, but I wouldn't rely on such behaviors.

        System.out.println(
            "1234".replaceAll(".(?<=(^.*))", "$1!")
        ); // prints "1!12!123!1234!"
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 02:19
    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();
                try{
                    Pattern.compile(pattern);
                    System.out.println("Valid");
                }catch(PatternSyntaxException exception){
                    System.out.println("Invalid");
                }
    
            }
        }
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-05 02:27

    Most obvious thing to do would be using compile method in java.util.regex.Pattern and catch PatternSyntaxException

    String myRegEx;
    ...
    ...
    Pattern p = Pattern.compile(myRegEx);
    

    This will throw a PatternSyntaxException if myRegEx is invalid.

    0 讨论(0)
  • 2020-12-05 02:27
     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();
          try
          {
              Pattern.compile(pattern);
          }
          catch(Exception e)
          {
             // System.out.println(e.toString());
              System.out.println("Invalid");
          }
          System.out.println("Valid");
        }
     }
    }
    
    0 讨论(0)
提交回复
热议问题