How to check if a given Regex is valid?

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.


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


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!"

Tags:

Java

Regex