繁体   English   中英

python 中的递归正则表达式 function 代码有什么问题

[英]What's wrong with recursive Regex function code in python

我写了一个正则表达式代码来比较两个字符串。 它识别一个特殊字符'?' 允许前一个字符的零个或多个实例。 它工作正常,直到出现两次或更多次“?” 在字符串中。 我不知道为什么。

def single_character_string(a, b) -> "return True if characters match":
    """check if two characters match"""
    if len(a) == 0:
        return True
    elif len(b) == 0:
        return False
    else:
        if a == '.':
            return True
        else:
            if a == b:
                return True
            else:
                return False


def meta_question_result(temp):
    if len(temp) >= 2:
        if temp[1] == '?':
            k_1 = temp.replace(temp[0: 2], '')  # no char
            k_2 = temp.replace(temp[1], '')  # char
            return k_1, k_2


def check_pair_by_pair(template, check_string) -> "Strings are of Equal length! " \
                                                  "return True if lines are identical":
    """check if two strings match symbol by symbol. template may be less than string, the opposite
    is False"""
    if not template:  # exit from recursion
        return True
    if not check_string:  # exit from recursion
        return False
    if meta_question_result(template):
        t_1, t_2 = meta_question_result(template)
        if single_character_string(t_1[0], check_string[0]):
            return check_pair_by_pair(t_1[1:], check_string[1:])
        if single_character_string(t_2[0], check_string[0]):
            return check_pair_by_pair(t_2[1:], check_string[1:])
        else:
            return False
    elif single_character_string(template[0], check_string[0]):
        return check_pair_by_pair(template[1:], check_string[1:])
    else:
        return False

reg, st = input().split("|")
print(check_pair_by_pair(reg, st))

reg = "co?lou?r" st = "颜色"

按预期给出 True,

reg = "co?lou?r" st = "clor"

按预期给出 True,

但...

reg = "co?lou?r" st = "颜色"

给出假。 我期待真实。

找到包了

Replace 方法替换“?”的所有实例。 那么第二个“?” 也被替换了,程序没有看到它。 我应该添加一个参数“count”来替换等于 1 的方法。

k_1 = temp.replace(temp[0: 2], '', 1) # 没有字符

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM