首页 > 解决方案 > 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。

标签: pythonpython-3.xpyqtpyqt5qregexp

解决方案


我不是正则表达式的专家,但使用 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_()) 

在此处输入图像描述


推荐阅读