I want to be able to validate a user's inputted regex, to check if it's valid or not. First thing I found with PHP's filter_var
with the FILTER_VALIDATE_REGEXP
constant but that doesn't do what I want since it must pass a regex to the options but I'm not regex'ing against anything so basically it's just checking the regex validity.
But you get the idea, how do I validate a user's inputted regex (that matches against nothing).
Example of validating, in simple words:
$user_inputted_regex = $_POST['regex']; // e.g. /([a-z]+)\..*([0-9]{2})/i
if(is_valid_regex($user_inputted_regex))
{
// The regex was valid
}
else
{
// The regex was invalid
}
Examples of validation:
/[[0-9]/i // invalid
//(.*)/ // invalid
/(.*)-(.*)-(.*)/ // valid
/([a-z]+)-([0-9_]+)/i // valid
new String(). matches(regEx) can be directly be used with try-catch to identify if regEx is valid. While this does accomplish the end result, Pattern. compile(regEx) is simpler (and is exactly what will end up happening anyway) and doesn't have any additional complexity.
Like PHP, many other programming languages have their own implementation of regular expressions. This is the same with other applications also, which have their own support of regexes having various syntaxes.
PHP's Regexp PERL Compatible Functions The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise. The preg_match_all() function matches all occurrences of pattern in string.
Here's an idea (demo):
function is_valid_regex($pattern)
{
return is_int(@preg_match($pattern, ''));
}
preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match.
preg_match() returns FALSE if an error occurred.
And to get the reason why the pattern isn't valid, use preg_last_error
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With