python - QRegExp 和 QSyntaxHighlighter 的单引号文本

标签 python python-3.x pyqt pyqt5 qregexp

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

测试模式

string1 = 'test' and string2 = 'ajsijd'

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

QRegExp("\'.*\'")

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

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

我正在使用 Python 3.6 和 PyQt5。

最佳答案

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

enter image description here

关于python - QRegExp 和 QSyntaxHighlighter 的单引号文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52765697/

相关文章:

python - 在 Cython 中使用 pyqt 类(.pyx 文件)

python - QFileDialog opens in new window while adding it to QHBoxLayout

python - 在 Python 中初始化对象列表

python - 如何在不发出示例请求的情况下检查 requests.Session 是否已通过身份验证?

Python 输入和输出线程

python - 更改Python中多个函数中的局部变量?

python - django中循环导入错误

python - PyQt5 setText 按对象名称?

Python,多线程,抓取网页,下载网页

python - pandas 与 numpy 的不同标准