How to write a regex to decide whether a regex is legal or illegal?
e.g. regex start with * is illegal. So the regex match legal regex may be [^\*]+[\s\S]*.
How to write a regex to decide whether a regex is legal or illegal?
e.g. regex start with * is illegal. So the regex match legal regex may be [^\*]+[\s\S]*.
Regular expressions are meant to match regular languages and since regular expressions aren't, you cannot achieve this. You should probably be using a Parser for this task.
However, programming languages that supports regular expressions have a built-in parser already and you could probably determine if the regular expression is valid or not by trying to instanciate one with the pattern you want to validate.
For instance, in JavaScript you could do something like:
function isValidRegex(regex) {
try {
new RegExp(regex)
}
catch (e) {
return false;
}
return true;
}
isValidRegex('*a'); //false
This is not possible without using recursive (ex. PCRE) regex. The set of all possible regular expressions is not a regular language.