Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the input string is a valid Regular expression?

How do you check, in JavaScript, if a string is a proper regular expression that will compile?

For example, when you execute the following javascript, it produces an error.

var regex = new RegExp('abc ([a-z]+) ([a-z]+))'); // produces: // Uncaught SyntaxError: Invalid regular expression: /abc ([a-z]+) ([a-z]+))/: Unmatched ')' 

How does one determine if a string will be a valid regex or not?

like image 898
Jak Samun Avatar asked Jun 22 '13 12:06

Jak Samun


People also ask

How do you check if a string is a regular expression in Python?

For checking if a string consists only of alphanumerics using module regular expression or regex, we can call the re. match(regex, string) using the regex: "^[a-zA-Z0-9]+$". re. match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().

Is there a regular expression to detect a valid regular expression?

No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars. There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes.


2 Answers

Here is a little function that checks the validity of both types of regexes, strings or patterns:

function validateRegex(pattern) {     var parts = pattern.split('/'),         regex = pattern,         options = "";     if (parts.length > 1) {         regex = parts[1];         options = parts[2];     }     try {         new RegExp(regex, options);         return true;     }     catch(e) {         return false;     } } 

The user will be able to test both test and /test/g for example. Here is a working fiddle.

like image 23
Niccolò Campolungo Avatar answered Oct 09 '22 03:10

Niccolò Campolungo


You can use try/catch and the RegExp constructor:

var isValid = true; try {     new RegExp("the_regex_to_test_goes_here"); } catch(e) {     isValid = false; }  if(!isValid) alert("Invalid regular expression"); 
like image 200
Jon Avatar answered Oct 09 '22 04:10

Jon