QSyntaxHighlighter的QRegExp和单引号文本 [英] QRegExp and single-quoted text for QSyntaxHighlighter

查看:240
本文介绍了QSyntaxHighlighter的QRegExp和单引号文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

QRegExp模式用于捕获QSyntaxHighlighter的单引号文字是什么?匹配项应包含引号,因为我正在构建sql代码编辑器.

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.

测试模式

string1 ='test'和string2 ='ajsijd'

string1 = 'test' and string2 = 'ajsijd'

到目前为止,我已经尝试过:

So far I have tried:

QRegExp("\'.*\'")

我在此正则表达式测试器上工作: https://regex101.com/r/eq7G1v/2 但是当我尝试在python中使用该正则表达式时,它可能无法工作,可能是因为我需要转义一个字符吗?

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

我正在使用Python 3.6和PyQt5.

I am using Python 3.6 and PyQt5.

推荐答案

我不是正则表达式方面的专家,但使用的是 C++ answer 来检测双引号之间的文本,将其更改为单引号,我会看到它的工作原理:

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

这篇关于QSyntaxHighlighter的QRegExp和单引号文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆