QRegExp and single-quoted text for QSyntaxHighlighter

核能气质少年 提交于 2020-01-30 10:02:35

问题


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



来源:https://stackoverflow.com/questions/52765697/qregexp-and-single-quoted-text-for-qsyntaxhighlighter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!