Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a given Regex is valid?

Tags:

java

regex

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 wondering if there is a build-in method in Java, but could not find such jet.

Can you give me some advice?

like image 533
Philipp Andre Avatar asked Apr 24 '10 14:04

Philipp Andre


People also ask

How do you validate a regex pattern?

RegEx pattern validation can be added to text input type questions. To add validation, click on the Validation icon on the text input type question.

How do you check whether a regex is valid or not in Python?

fullmatch(). This method checks if the whole string matches the regular expression pattern or not. If it does then it returns 1, otherwise a 0.

What is invalid regex?

The JavaScript exception "invalid regular expression flag" occurs when the flags in a regular expression contain any flag that is not one of: g , i , m , s , u , y or d .

What is regex validator?

RegEx validation is essentially a syntax check which makes it possible to see whether an email address is spelled correctly, has no spaces, commas, and all the @s, dots and domain extensions are in the right place.


1 Answers

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.

like image 62
laz Avatar answered Sep 21 '22 15:09

laz