python - QSyntaxHighlighter 的 QRegExp 和单引号文本
问题描述
QRegExp 模式用于为 QSyntaxHighlighter 捕获单引号文本是什么?匹配应该包括引号,因为我正在构建一个 sql 代码编辑器。
测试图案
string1 = 'test' 和 string2 = 'ajsijd'
到目前为止,我已经尝试过:
QRegExp("\'.*\'")
我让它在这个正则表达式测试器上工作:https ://regex101.com/r/eq7G1v/2 但是当我尝试在 python 中使用该正则表达式时它不起作用可能是因为我需要转义一个字符?
self.highlightingRules.append((QRegExp("(['])(?:(?=(\\?))\2.)*?\1"), quotationFormat))
我正在使用 Python 3.6 和 PyQt5。
解决方案
我不是正则表达式的专家,但使用 aC++ answer
来检测双引号之间的文本,将其更改为单引号,我发现它有效:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class SyntaxHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, parent=None):
super(SyntaxHighlighter, self).__init__(parent)
keywordFormat = QtGui.QTextCharFormat()
keywordFormat.setForeground(QtCore.Qt.darkBlue)
keywordFormat.setFontWeight(QtGui.QFont.Bold)
keywordPatterns = ["'([^'']*)'"]
self.highlightingRules = [(QtCore.QRegExp(pattern), keywordFormat)
for pattern in keywordPatterns]
def highlightBlock(self, text):
for pattern, _format in self.highlightingRules:
expression = QtCore.QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, _format)
index = expression.indexIn(text, index + length)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
editor = QtWidgets.QTextEdit()
editor.append("string1 = 'test' and string2 = 'ajsijd'")
highlighter = SyntaxHighlighter(editor.document())
editor.show()
sys.exit(app.exec_())
推荐阅读
- python - 在同一路由中返回 Python Flask 中的多个语句
- heroku - 运行 Cloudinary 插件与现有的带有载波集成的 RoR 相比有什么好处吗
- python-3.x - 逐个循环播放jpgs以下载到计算机
- apache-spark - 如何提交不同语言的 Spark 应用程序?
- python - 函数内部的变量是通过对象全局还是局部访问?[Python]
- visual-studio-code - 一个标准输出如何通过管道传输到父进程的标准输出?
- c# - 如何以编程方式绑定生成的组合框
- ansible - Ansible 剧本替换模块未按预期运行
- c# - 使用资源字符串进行枚举序列化
- javascript - 在 REACT.js 中,如何将状态从子组件传递到父组件作为道具