首页 > 解决方案 > 算法检查字符串是否缺少右引号( ', " OR ` )

问题描述

检查给定字符串的python的最佳方法是什么,其中没有开引号?

例如

// missing quote
bar, fun("foo"), "zaa 

// OK quote
bar, fun("foo), "zaa 

// missing quote
bar, fun("foo), zaa 


// ok quote (single quote encompasses both ends)
bar', fun("foo), zaa' 


// ok quote since there is the escape
bar', \'fun("foo), zaa' 

// missing quote since there is the escape
bar', \'fun("foo), zaa 

// missing quote
bar', fun("foo"), zaa 

我试图运行类似的东西

regexp(raw, '"(^".*?)"', my_string)
regexp(raw, '`(^`.*?)`', my_string)
regexp(raw, '\'(^\'.*?)\'', my_string)

但这仅检测字符串是否正确关闭

这是另一次尝试,但我仍在尝试提出一个清晰的逻辑来检测所有先前的报价已经关闭

regexp(raw, '"(^".*?)$', my_string)

标签: pythonregexstringalgorithm

解决方案


您可能不使用正则表达式,只需使用堆栈来检查它。这个问题是一种正确的括号检查问题。

UPD:更新引号字符

UPD2:正则表达式不是这种情况下的完美工具

def is_quote_ok(s):
    stack = []
    for c in s:
        if c in ["'", '"', "`"]:
            if stack and stack[-1] == c:
                # this single-quote is close character
                stack.pop()
            else:
                # a new quote started
                stack.append(c)
        else:
            # ignore it
            pass

    return len(stack) == 0

推荐阅读