本文整理汇总了Python中PyQt5.QtCore.QRegExp.matchedLength方法的典型用法代码示例。如果您正苦于以下问题:Python QRegExp.matchedLength方法的具体用法?Python QRegExp.matchedLength怎么用?Python QRegExp.matchedLength使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtCore.QRegExp
的用法示例。
在下文中一共展示了QRegExp.matchedLength方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: highlightBlock
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
def highlightBlock(self, text):
for pattern, format in self.rules:
exp = QRegExp(pattern)
index = exp.indexIn(text)
while index >= 0:
length = exp.matchedLength()
if exp.numCaptures() > 0:
self.setFormat(exp.pos(1), len(str(exp.cap(1))), format)
else:
self.setFormat(exp.pos(0), len(str(exp.cap(0))), format)
index = exp.indexIn(text, index + length)
# Multi line strings
start = self.multilineStart
end = self.multilineEnd
self.setCurrentBlockState(0)
startIndex, skip = 0, 0
if self.previousBlockState() != 1:
startIndex, skip = start.indexIn(text), 3
while startIndex >= 0:
endIndex = end.indexIn(text, startIndex + skip)
if endIndex == -1:
self.setCurrentBlockState(1)
commentLen = len(text) - startIndex
else:
commentLen = endIndex - startIndex + 3
self.setFormat(startIndex, commentLen, self.stringFormat)
startIndex, skip = (start.indexIn(text,
startIndex + commentLen + 3),
3)
示例2: highlightBlock
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
def highlightBlock(self, text):
for pattern, format in self.highlightingRules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, format)
index = expression.indexIn(text, index + length)
self.setCurrentBlockState(0)
startIndex = 0
if self.previousBlockState() != 1:
startIndex = self.commentStartExpression.indexIn(text)
while startIndex >= 0:
endIndex = self.commentEndExpression.indexIn(text, startIndex)
if endIndex == -1:
self.setCurrentBlockState(1)
commentLength = len(text) - startIndex
else:
commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()
self.setFormat(startIndex, commentLength,
self.multiLineCommentFormat)
startIndex = self.commentStartExpression.indexIn(text,
startIndex + commentLength);
示例3: refresh
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
def refresh(self):
self.setUpdatesEnabled(False)
pattern = self.patternComboBox.currentText()
text = self.textComboBox.currentText()
escaped = str(pattern)
escaped.replace('\\', '\\\\')
escaped.replace('"', '\\"')
self.escapedPatternLineEdit.setText('"' + escaped + '"')
rx = QRegExp(pattern)
cs = Qt.CaseSensitive if self.caseSensitiveCheckBox.isChecked() else Qt.CaseInsensitive
rx.setCaseSensitivity(cs)
rx.setMinimal(self.minimalCheckBox.isChecked())
syntax = self.syntaxComboBox.itemData(self.syntaxComboBox.currentIndex())
rx.setPatternSyntax(syntax)
palette = self.patternComboBox.palette()
if rx.isValid():
palette.setColor(QPalette.Text,
self.textComboBox.palette().color(QPalette.Text))
else:
palette.setColor(QPalette.Text, Qt.red)
self.patternComboBox.setPalette(palette)
self.indexEdit.setText(str(rx.indexIn(text)))
self.matchedLengthEdit.setText(str(rx.matchedLength()))
for i in range(self.MaxCaptures):
self.captureLabels[i].setEnabled(i <= rx.captureCount())
self.captureEdits[i].setEnabled(i <= rx.captureCount())
self.captureEdits[i].setText(rx.cap(i))
self.setUpdatesEnabled(True)
示例4: XmlSyntaxHighlighter
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
class XmlSyntaxHighlighter(QSyntaxHighlighter):
def __init__(self, parent=None):
super(XmlSyntaxHighlighter, self).__init__(parent)
self.highlightingRules = []
# Tag format.
format = QTextCharFormat()
format.setForeground(Qt.darkBlue)
format.setFontWeight(QFont.Bold)
pattern = QRegExp("(<[a-zA-Z:]+\\b|<\\?[a-zA-Z:]+\\b|\\?>|>|/>|</[a-zA-Z:]+>)")
self.highlightingRules.append((pattern, format))
# Attribute format.
format = QTextCharFormat()
format.setForeground(Qt.darkGreen)
pattern = QRegExp("[a-zA-Z:]+=")
self.highlightingRules.append((pattern, format))
# Attribute content format.
format = QTextCharFormat()
format.setForeground(Qt.red)
pattern = QRegExp("(\"[^\"]*\"|'[^']*')")
self.highlightingRules.append((pattern, format))
# Comment format.
self.commentFormat = QTextCharFormat()
self.commentFormat.setForeground(Qt.lightGray)
self.commentFormat.setFontItalic(True)
self.commentStartExpression = QRegExp("<!--")
self.commentEndExpression = QRegExp("-->")
def highlightBlock(self, text):
for pattern, format in self.highlightingRules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, format)
index = expression.indexIn(text, index + length)
self.setCurrentBlockState(0)
startIndex = 0
if self.previousBlockState() != 1:
startIndex = self.commentStartExpression.indexIn(text)
while startIndex >= 0:
endIndex = self.commentEndExpression.indexIn(text, startIndex)
if endIndex == -1:
self.setCurrentBlockState(1)
commentLength = text.length() - startIndex
else:
commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()
self.setFormat(startIndex, commentLength, self.commentFormat)
startIndex = self.commentStartExpression.indexIn(text,
startIndex + commentLength)
示例5: findIndex
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
def findIndex(self, position=0):
""" Return the index and the length of the first match found after
"position".
When the end of the document is reached, the search continues from the
beginning. Return [None, None] when no match is found.
Parameters
----------
self : QWidget
position : int optional
Position in the text used as start point for the search.
"""
# avoid to search fpr an empty pattern
if self.regex.text() == '':
return None, None
# create the regex object and the text cursor position object
regex = QRegExp(self.regex.text())
cursor = self.pageContent.textCursor()
# find first occourrence after the cursor
index = regex.indexIn(
self.pageContent.toPlainText(),
position)
length = regex.matchedLength()
if position != 0 and index < 0:
# no match found, try from the document beginning
index = regex.indexIn(
self.pageContent.toPlainText(),
0)
length = regex.matchedLength()
if index < 0:
# no match: there is no occourrence
return None, None
return index, length
示例6: findAllIndices
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
def findAllIndices(self):
""" Return three lists containing the absolute starting
position, the length and the replacement text for each match in the
whole text, starting from its beginning.
"""
# avoid to search for an empty pattern
if self.regex.text() == '':
return None, None, None
regex = QRegExp(self.regex.text())
index = 0
indices = []
lengths = []
replacements = []
while True:
# find next occourrence
index = regex.indexIn(
self.pageContent.toPlainText(),
index)
length = regex.matchedLength()
if index < 0:
return indices, lengths, replacements
# get replacement text
replacement = re.sub(
self.regex.text(),
self.replacement.text(),
self.pageContent.toPlainText()[index : index + length],
1)
# append to result
indices.append(index)
lengths.append(length)
replacements.append(replacement)
# continue search after the match
index = index + length
示例7: highlightBlock
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
def highlightBlock(self, text):
""" Reimplementation """
block_data = TextBlockData()
# Paren
index = self.paren.indexIn(text, 0)
while index >= 0:
matched_paren = str(self.paren.capturedTexts()[0])
info = ParenInfo(matched_paren, index)
block_data.insert_paren_info(info)
index = self.paren.indexIn(text, index + 1)
self.setCurrentBlockUserData(block_data)
for pattern, _format in self._rules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, _format)
index = expression.indexIn(text, index + length)
self.setCurrentBlockState(0)
示例8: Highlighter
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
class Highlighter(QSyntaxHighlighter):
def __init__(self, parent=None):
super(Highlighter, self).__init__(parent)
keywordFormat = QTextCharFormat()
keywordFormat.setForeground(Qt.darkBlue)
keywordFormat.setFontWeight(QFont.Bold)
keywordPatterns = ["\\bchar\\b", "\\bclass\\b", "\\bconst\\b",
"\\bdouble\\b", "\\benum\\b", "\\bexplicit\\b", "\\bfriend\\b",
"\\binline\\b", "\\bint\\b", "\\blong\\b", "\\bnamespace\\b",
"\\boperator\\b", "\\bprivate\\b", "\\bprotected\\b",
"\\bpublic\\b", "\\bshort\\b", "\\bsignals\\b", "\\bsigned\\b",
"\\bslots\\b", "\\bstatic\\b", "\\bstruct\\b",
"\\btemplate\\b", "\\btypedef\\b", "\\btypename\\b",
"\\bunion\\b", "\\bunsigned\\b", "\\bvirtual\\b", "\\bvoid\\b",
"\\bvolatile\\b"]
self.highlightingRules = [(QRegExp(pattern), keywordFormat)
for pattern in keywordPatterns]
classFormat = QTextCharFormat()
classFormat.setFontWeight(QFont.Bold)
classFormat.setForeground(Qt.darkMagenta)
self.highlightingRules.append((QRegExp("\\bQ[A-Za-z]+\\b"),
classFormat))
singleLineCommentFormat = QTextCharFormat()
singleLineCommentFormat.setForeground(Qt.red)
self.highlightingRules.append((QRegExp("//[^\n]*"),
singleLineCommentFormat))
self.multiLineCommentFormat = QTextCharFormat()
self.multiLineCommentFormat.setForeground(Qt.red)
quotationFormat = QTextCharFormat()
quotationFormat.setForeground(Qt.darkGreen)
self.highlightingRules.append((QRegExp("\".*\""), quotationFormat))
functionFormat = QTextCharFormat()
functionFormat.setFontItalic(True)
functionFormat.setForeground(Qt.blue)
self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=\\()"),
functionFormat))
self.commentStartExpression = QRegExp("/\\*")
self.commentEndExpression = QRegExp("\\*/")
def highlightBlock(self, text):
for pattern, format in self.highlightingRules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, format)
index = expression.indexIn(text, index + length)
self.setCurrentBlockState(0)
startIndex = 0
if self.previousBlockState() != 1:
startIndex = self.commentStartExpression.indexIn(text)
while startIndex >= 0:
endIndex = self.commentEndExpression.indexIn(text, startIndex)
if endIndex == -1:
self.setCurrentBlockState(1)
commentLength = len(text) - startIndex
else:
commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()
self.setFormat(startIndex, commentLength,
self.multiLineCommentFormat)
startIndex = self.commentStartExpression.indexIn(text,
startIndex + commentLength);
示例9: Highlighter
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
class Highlighter(QSyntaxHighlighter):
def __init__(self, parent):
super(Highlighter, self).__init__(parent)
self.highlightingRules = []
self.commentStartExpression = QRegExp()
self.commentEndExpression = QRegExp()
self.keywordFormat = QTextCharFormat()
self.classFormat = QTextCharFormat()
self.singleLineCommentFormat = QTextCharFormat()
self.multiLineCommentFormat = QTextCharFormat()
self.quotationFormat = QTextCharFormat()
self.functionFormat = QTextCharFormat()
self.keywordFormat.setForeground(Qt.darkBlue)
self.keywordFormat.setFontWeight(QFont.Bold)
keywords = [
"char",
"class",
"const",
"double",
"enum",
"explicit",
"friend",
"inline",
"int",
"long",
"namespace",
"operator",
"private",
"protected",
"public",
"short",
"signals",
"signed",
"slots",
"static",
"struct",
"template",
"typedef",
"typename",
"union",
"unsigned",
"virtual",
"void",
"volatile",
]
for keyword in keywords:
self.highlightingRules.append(Rule(QRegExp("\\b%s\\b" % keyword), self.keywordFormat))
self.classFormat.setFontWeight(QFont.Bold)
self.classFormat.setForeground(Qt.darkMagenta)
self.highlightingRules.append(Rule(QRegExp("Q[A-Za-z]+"), self.classFormat))
self.singleLineCommentFormat.setForeground(Qt.red)
self.highlightingRules.append(Rule(QRegExp("//[^\n]*"), self.singleLineCommentFormat))
self.multiLineCommentFormat.setForeground(Qt.red)
self.quotationFormat.setForeground(Qt.darkGreen)
self.highlightingRules.append(Rule(QRegExp("'.*'"), self.quotationFormat))
self.functionFormat.setFontItalic(True)
self.functionFormat.setForeground(Qt.blue)
self.highlightingRules.append(Rule(QRegExp("[A-Za-z0-9_]+(?=\\()"), self.functionFormat))
self.commentStartExpression = QRegExp("/\\*")
self.commentEndExpression = QRegExp("\\*/")
def highlightBlock(self, text):
for rule in self.highlightingRules:
expression = QRegExp(rule.pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, rule.format)
index = expression.indexIn(text, index + length)
self.setCurrentBlockState(0)
startIndex = 0
if self.previousBlockState() != 1:
startIndex = self.commentStartExpression.indexIn(text)
while startIndex >= 0:
endIndex = self.commentEndExpression.indexIn(text, startIndex)
if endIndex == -1:
self.setCurrentBlockState(1)
commentLength = len(text) - startIndex
else:
commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()
self.setFormat(startIndex, commentLength, self.multiLineCommentFormat)
startIndex = self.commentStartExpression.indexIn(text, startIndex + commentLength)
示例10: highlightBlock
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
#.........这里部分代码省略.........
# If it's a setting, we might do something
if state == State.SETTINGS_LINE:
# Target
r = QRegExp(r'^%!([^\s]+)\s*:\s*(\b\w*\b)$')
if r.indexIn(text) != -1:
setting = r.cap(1)
val = r.cap(2)
if setting == "target" and \
val in self.editor.main.targetsNames:
self.editor.fileWidget.preview.setPreferredTarget(val)
# Pre/postproc
r = QRegExp(r'^%!p[or][se]t?proc[^\s]*\s*:\s*((\'[^\']*\'|\"[^\"]*\")\s*(\'[^\']*\'|\"[^\"]*\"))')
if r.indexIn(text) != -1:
p = r.pos(1)
length = len(r.cap(1))
self.setFormat(p, length, self.style.makeFormat(base=self.format(p),
fixedPitch=True))
# Tables
for lineState in [State.TABLE_LINE, State.TABLE_HEADER]:
if state == lineState:
for i, t in enumerate(text):
if t == "|":
self.setFormat(i, 1, op)
else:
self.setFormat(i, 1, self.style.format(lineState))
# Lists
# if text == " p": print(data.isList())
if data.isList():
r = QRegExp(r'^\s*[\+\-\:]? ?')
r.indexIn(text)
self.setFormat(0, r.matchedLength(), self.style.format(State.LIST_BULLET))
# if state == State.LIST_BEGINS:
# r = QRegExp(r'^\s*[+-:] ')
# r.indexIn(text)
# self.setFormat(0, r.matchedLength(), self.style.format(State.LIST_BULLET))
if state == State.LIST_ENDS:
self.setFormat(0, len(text), self.style.format(State.LIST_BULLET_ENDS))
# Titles
if not inList and state in State.TITLES:
r = [i for (i, s) in State.Rules if s == state][0]
pos = r.indexIn(text)
if pos >= 0:
f = self.style.format(state)
# Uncomment for markup to be same size as title
# op = self.formats(preset="markup",
# base=self.formats(preset=state))
self.setFormat(r.pos(2), len(r.cap(2)), f)
self.setFormat(r.pos(1), len(r.cap(1)), op)
self.setFormat(r.pos(3), len(r.cap(3)), op)
# Areas: comment, code, raw tagged
for (begins, middle, ends) in [
(State.COMMENT_AREA_BEGINS, State.COMMENT_AREA, State.COMMENT_AREA_ENDS),
(State.CODE_AREA_BEGINS, State.CODE_AREA, State.CODE_AREA_ENDS),
(State.RAW_AREA_BEGINS, State.RAW_AREA, State.RAW_AREA_ENDS),
(State.TAGGED_AREA_BEGINS, State.TAGGED_AREA, State.TAGGED_AREA_ENDS),
]:
if state == middle:
self.setFormat(0, len(text), self.style.format(middle))
elif state in [begins, ends]:
示例11: on_executeButton_clicked
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
def on_executeButton_clicked(self, startpos=0):
"""
Private slot to execute the entered regexp on the test text.
This slot will execute the entered regexp on the entered test
data and will display the result in the table part of the dialog.
@param startpos starting position for the regexp matching
"""
regex = self.regexpLineEdit.text()
text = self.textTextEdit.toPlainText()
if regex and text:
re = QRegExp(regex)
if self.caseSensitiveCheckBox.isChecked():
re.setCaseSensitivity(Qt.CaseSensitive)
else:
re.setCaseSensitivity(Qt.CaseInsensitive)
re.setMinimal(self.minimalCheckBox.isChecked())
syntax = self.syntaxCombo.itemData(self.syntaxCombo.currentIndex())
wildcard = syntax in [QRegExp.Wildcard, QRegExp.WildcardUnix]
re.setPatternSyntax(syntax)
if not re.isValid():
E5MessageBox.critical(
self,
self.tr("Error"),
self.tr("""Invalid regular expression: {0}""")
.format(re.errorString()))
return
offset = re.indexIn(text, startpos)
captures = re.captureCount()
row = 0
OFFSET = 5
self.resultTable.setColumnCount(0)
self.resultTable.setColumnCount(3)
self.resultTable.setRowCount(0)
self.resultTable.setRowCount(OFFSET)
self.resultTable.setItem(
row, 0, QTableWidgetItem(self.tr("Regexp")))
self.resultTable.setItem(row, 1, QTableWidgetItem(regex))
if offset != -1:
self.lastMatchEnd = offset + re.matchedLength()
self.nextButton.setEnabled(True)
row += 1
self.resultTable.setItem(
row, 0, QTableWidgetItem(self.tr("Offset")))
self.resultTable.setItem(
row, 1, QTableWidgetItem("{0:d}".format(offset)))
if not wildcard:
row += 1
self.resultTable.setItem(
row, 0, QTableWidgetItem(self.tr("Captures")))
self.resultTable.setItem(
row, 1, QTableWidgetItem("{0:d}".format(captures)))
row += 1
self.resultTable.setItem(
row, 1, QTableWidgetItem(self.tr("Text")))
self.resultTable.setItem(
row, 2, QTableWidgetItem(self.tr("Characters")))
row += 1
self.resultTable.setItem(
row, 0, QTableWidgetItem(self.tr("Match")))
self.resultTable.setItem(
row, 1, QTableWidgetItem(re.cap(0)))
self.resultTable.setItem(
row, 2,
QTableWidgetItem("{0:d}".format(re.matchedLength())))
if not wildcard:
for i in range(1, captures + 1):
if len(re.cap(i)) > 0:
row += 1
self.resultTable.insertRow(row)
self.resultTable.setItem(
row, 0,
QTableWidgetItem(
self.tr("Capture #{0}").format(i)))
self.resultTable.setItem(
row, 1,
QTableWidgetItem(re.cap(i)))
self.resultTable.setItem(
row, 2,
QTableWidgetItem(
"{0:d}".format(len(re.cap(i)))))
else:
self.resultTable.setRowCount(3)
# highlight the matched text
tc = self.textTextEdit.textCursor()
tc.setPosition(offset)
tc.setPosition(self.lastMatchEnd, QTextCursor.KeepAnchor)
self.textTextEdit.setTextCursor(tc)
else:
self.nextButton.setEnabled(False)
self.resultTable.setRowCount(2)
row += 1
if startpos > 0:
#.........这里部分代码省略.........
示例12: Highlighter
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
class Highlighter(QSyntaxHighlighter):
def __init__(self, parent=None):
super(Highlighter, self).__init__(parent)
keywordFormat = QTextCharFormat()
keywordFormat.setForeground(Qt.darkBlue)
keywordFormat.setFontWeight(QFont.Bold)
keywordPatterns = ["""</?\w+\s+[^>]*>""","<[/]?(html|body|head|title|div|a|br|form|input|b|p|i|center|span|font|table|tr|td|h[1-6])[/]?>"]
self.highlightingRules = [(QRegExp(pattern), keywordFormat)
for pattern in keywordPatterns]
self.multiLineCommentFormat = QTextCharFormat()
self.multiLineCommentFormat.setForeground(Qt.red)
quotationFormat = QTextCharFormat()
quotationFormat.setForeground(Qt.darkGreen)
self.highlightingRules.append((QRegExp("\".*\""),
quotationFormat))
functionFormat = QTextCharFormat()
functionFormat.setFontItalic(True)
functionFormat.setForeground(Qt.blue)
self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=\\()"),
functionFormat))
moreKeyWords = QTextCharFormat()
moreKeyWords.setForeground(Qt.darkMagenta)
moreKeyWords.setFontWeight(QFont.Bold)
self.highlightingRules.append((QRegExp("(id|class|src|border|width|height|style|name|type|value)="),moreKeyWords))
self.commentStartExpression = QRegExp("<!--")
self.commentEndExpression = QRegExp("-->")
def highlightBlock(self, text):
for pattern, formats in self.highlightingRules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, formats)
index = expression.indexIn(text, index + length)
self.setCurrentBlockState(0)
startIndex = 0
if self.previousBlockState() != 1:
startIndex = self.commentStartExpression.indexIn(text)
while startIndex >= 0:
endIndex = self.commentEndExpression.indexIn(text, startIndex)
if endIndex == -1:
self.setCurrentBlockState(1)
commentLength = len(text) - startIndex
else:
commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()
self.setFormat(startIndex, commentLength,
self.multiLineCommentFormat)
startIndex = self.commentStartExpression.indexIn(text,
startIndex + commentLength);
示例13: Highlighter
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import matchedLength [as 别名]
class Highlighter(QSyntaxHighlighter):
def __init__(self, parent=None):
super(Highlighter, self).__init__(parent)
keywordFormat = QTextCharFormat()
keywordFormat.setForeground(Qt.darkYellow)
keywordFormat.setFontWeight(QFont.Bold)
keywordPatterns = ["\\bFalse\\b", "\\bNone\\b", "\\bTrue\\b","\\band\\b", "\\bas\\b", "\\bassert\\b",
"\\bbreak\\b", "\\bclass\\b", "\\bcontinue\\b", "\\bdef\\b",
"\\bdel\\b", "\\belif\\b", "\\belse\\b", "\\bexcept\\b",
"\\bfinally\\b", "\\bfor\\b", "\\bfrom\\b",
"\\bglobal\\b", "\\bif\\b", "\\bimport\\b", "\\bin\\b",
"\\bis\\b", "\\blambda\\b", "\\bnonlocal\\b",
"\\bnot\\b", "\\bor\\b", "\\bpass\\b",
"\\braise\\b", "\\breturn\\b", "\\btry\\b", "\\bwhile\\b",
"\\bwith\\b", "\\byield\\b"]
self.highlightingRules = [(QRegExp(pattern), keywordFormat)
for pattern in keywordPatterns]
commentFormat = QTextCharFormat()
commentFormat.setFontWeight(QFont.Bold)
commentFormat.setForeground(Qt.black)
self.highlightingRules.append((QRegExp("\\b#[^\n]*\\b"),
commentFormat))
singleLineCommentFormat = QTextCharFormat()
singleLineCommentFormat.setForeground(Qt.red)
self.highlightingRules.append((QRegExp("//[^\n]*"),singleLineCommentFormat))
self.multiLineCommentFormat = QTextCharFormat()
self.multiLineCommentFormat.setForeground(Qt.red)
quotationFormat = QTextCharFormat()
quotationFormat.setForeground(Qt.darkGreen)
self.highlightingRules.append((QRegExp("\".*\""), quotationFormat))
functionFormat = QTextCharFormat()
functionFormat.setFontItalic(True)
functionFormat.setForeground(Qt.blue)
self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=\\()"),
functionFormat))
self.commentStartExpression = QRegExp("/\\*")
self.commentEndExpression = QRegExp("\\*/")
def highlightBlock(self, text):
for pattern, format in self.highlightingRules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, format)
index = expression.indexIn(text, index + length)
self.setCurrentBlockState(0)
startIndex = 0
if self.previousBlockState() != 1:
startIndex = self.commentStartExpression.indexIn(text)
while startIndex >= 0:
endIndex = self.commentEndExpression.indexIn(text, startIndex)
if endIndex == -1:
self.setCurrentBlockState(1)
commentLength = len(text) - startIndex
else:
commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()
self.setFormat(startIndex, commentLength,
self.multiLineCommentFormat)
startIndex = self.commentStartExpression.indexIn(text,
startIndex + commentLength)