首页 > 其他 > 详细

回溯法实现正则匹配判断

时间:2019-07-14 16:44:22      阅读:84      评论:0      收藏:0      [点我收藏+]

*:匹配任意个字符

?:匹配至多1个字符

<?php

class MNode
{
    public $strIndex;
    public $patIndex;
    public $leftMatch = null;   //精确匹配
    public $midMatch = null;    //模式匹配
    public $rightMatch = null;  //不能匹配

    public function __construct($strIndex, $patIndex)
    {
        $this->strIndex = $strIndex;
        $this->patIndex = $patIndex;
    }
}

class RegMatch
{
    public $root, $match = false;
    public $string, $pattern;
    public $strLen, $patLen;

    public function __construct(string $string, string $pattern)
    {
        $this->root = new MNode(0, 0);
        $this->string = $string;
        $this->pattern = $pattern;
        $this->strLen = strlen($string);
        $this->patLen = strlen($pattern);
    }

    public function isMatch()
    {
        return $this->doMatch($this->root);
    }

    protected function doMatch($root)
    {
        static $matchCount = 0;

        if (empty($root) || empty($this->string) || empty($this->pattern) || $this->match == true
            || $root->strIndex >= $this->strLen || $root->patIndex >= $this->patLen) {
            if ($root->patIndex >= $this->patLen) {
                $this->match = true;
            }
            return $this->match;
        }

        if ($this->string[$root->strIndex] == $this->pattern[$root->patIndex]) {
            $root->leftMatch = new MNode($root->strIndex + 1, $root->patIndex + 1);
            $this->doMatch($root->leftMatch);
        }

        //模式情况
        if ($this->pattern[$root->patIndex] == ‘*‘) {
            $root->midMatch = new MNode($root->strIndex + 1, $root->patIndex + 1);
            $this->doMatch($root->midMatch);
            if ($this->match == false) {
                $root->rightMatch = new MNode($root->strIndex, $root->patIndex + 1);
                $this->doMatch($root->rightMatch);
            }
        }

        if ($this->pattern[$root->patIndex] == ‘?‘) {
            $root->rightMatch = new MNode($root->strIndex, $root->patIndex + 1);
            $this->doMatch($root->rightMatch);
            if ($this->match == false && $matchCount <= 1) {
                $matchCount++;
                $root->midMatch = new MNode($root->strIndex + 1, $root->patIndex + 1);
                $this->doMatch($root->midMatch);
            }
        }

        if ($this->match == false && $root->patIndex == 0) {
            $root->rightMatch = new MNode($root->strIndex + 1, $root->patIndex);
            $this->doMatch($root->rightMatch);
        }

        return $this->match;
    }
}

$obj = new RegMatch(‘abc‘, ‘*c‘);

echo $obj->isMatch();

 

回溯法实现正则匹配判断

原文:https://www.cnblogs.com/SHQHDMR/p/11184242.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!