python - 算法检查字符串是否缺少右引号( ', " 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)
解决方案
您可能不使用正则表达式,只需使用堆栈来检查它。这个问题是一种正确的括号检查问题。
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
推荐阅读
- r - 如何将 ff 对象传递给集群/节点
- snowflake-cloud-data-platform - 雪花:如何读取 JSON 格式但包装在 XML 响应中的数据
- bash - 如何将列表传递给另一个函数中的函数调用
- oracle-sqldeveloper - SQL Developer 20.1 中的格式问题
- java - 如何为 ImageView 创建一个 id
- python - 在 Python TextBlob 上:更新时限制模型的大小
- ruby-on-rails - 错误:尝试安装 Rails / Nokogiri 时无法构建 gem 原生扩展
- if-statement - Google 表格将 HTML 标记添加到单元格内的数字中
- node.js - 如何在节点,js中创建浏览器警报
- azure - 使用 .pfx 文件签署 JWT