QRegExp and single-quoted text for QSyntaxHighligh

2020-04-21 08:01发布

问题:

What would the QRegExp pattern be for capturing single quoted text for QSyntaxHighlighter? The matches should include the quotes, because I am building a sql code editor.

Test Pattern

string1 = 'test' and string2 = 'ajsijd'

So far I have tried:

QRegExp("\'.*\'")

I got it working on this regex tester: https://regex101.com/r/eq7G1v/2 but when I try to use that regex in python its not working probably because I need to escape a character?

self.highlightingRules.append((QRegExp("(['])(?:(?=(\\?))\2.)*?\1"), quotationFormat))

I am using Python 3.6 and PyQt5.

回答1:

I am not an expert in regex but using a C++ answer to detect texts between double quotes changing it to single quote I see that it works:

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_())