如何检查给定的字符串是否是有效的Regex


How to check if a given string is valid Regex?

可能重复:
在PHP 中测试正则表达式是否有效

 <?php 
    $subject = "PHP is the web scripting language of choice.";    
    $pattern = 'sssss';
    if(preg_match($pattern,$subject))
    {
        echo 'true';
    }
    else
    {
        echo 'false';
    }
?>

上面的代码向我发出警告,因为字符串$pattern不是有效的正则表达式。

如果我传递有效的正则表达式,那么它可以正常工作。。。。。

如何检查$pattern是有效的正则表达式?

如果Regexp出现问题,您可以编写一个抛出错误的函数。(在我看来应该是这样。(使用@来抑制警告是不好的做法,但如果用抛出的异常替换它,它应该是可以的

function my_preg_match($pattern,$subject)
{
    $match = @preg_match($pattern,$subject);
    if($match === false)
    {
        $error = error_get_last();
        throw new Exception($error['message']);
    }
    return false;
}

然后您可以使用检查regexp是否正确

$subject = "PHP is the web scripting language of choice.";    
$pattern = 'sssss';
try
{
    my_preg_match($pattern,$subject);
    $regexp_is_correct = true;
}
catch(Exception $e)
{
    $regexp_is_correct = false;
}

使用===运算符:

<?php 
    $subject = "PHP is the web scripting language of choice.";    
    $pattern = 'sssss';
    $r = preg_match($pattern,$subject);
    if($r === false)
    {
        // preg matching failed (most likely because of incorrect regex)
    }
    else
    {
        // preg match succeeeded, use $r for result (which can be 0 for no match)
        if ($r == 0) {
            // no match
        } else {
            // $subject matches $pattern
        }
    }
?>

您可以用try-catch包装preg_match,如果抛出异常,则将结果视为false。

无论如何,您可以查看正则表达式来检测有效的正则表达式。