Viewed   53 times

I'd like to test the validity of a regular expression in PHP, preferably before it's used. Is the only way to do this actually trying a preg_match() and seeing if it returns FALSE?

Is there a simpler/proper way to test for a valid regular expression?


// This is valid, both opening ( and closing )
var_dump(preg_match('~Valid(Regular)Expression~', null) === false);
// This is invalid, no opening ( for the closing )
var_dump(preg_match('~InvalidRegular)Expression~', null) === false);

As the user pozs said, also consider putting @ in front of preg_match() (@preg_match()) in a testing environment to prevent warnings or notices.

To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false (=== false), it's broken. Otherwise it's valid though it need not match anything.

So there's no need to write your own RegExp validator. It's wasted time...

Saturday, October 22, 2022

The Arabic regex is:


Actually, ?-? is a subset of this Arabic range, so I think you can remove them from the pattern.

So, in JS it will be


See regex demo

Tuesday, October 11, 2022

Use the following expression:



using System.Text.RegularExpressions;

Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(SomeString)) {
Friday, November 18, 2022

For this PHP regex:

$str = preg_replace ( '{(.)1+}', '$1', $str );
$str = preg_replace ( '{[ '-_()]}', '', $str )

In Java:

str = str.replaceAll("(.)\1+", "$1");
str = str.replaceAll("[ '-_\(\)]", "");

I suggest you to provide your input and expected output then you will get better answers on how it can be done in PHP and/or Java.

Sunday, October 9, 2022

No need for jQuery. Use the RegExp constructor and catch the exception :

try {
    new RegExp(someString);
} catch (e) {

Demonstration (type something in the input to know if it's a well formed regular expression)

Thursday, September 22, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :