回溯法实现正则匹配判断

*:匹配任意个字符

?:匹配至多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
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值