本文整理汇总了Python中PyQt5.QtCore.QRegExp.indexIn方法的典型用法代码示例。如果您正苦于以下问题:Python QRegExp.indexIn方法的具体用法?Python QRegExp.indexIn怎么用?Python QRegExp.indexIn使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtCore.QRegExp
的用法示例。
在下文中一共展示了QRegExp.indexIn方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __filterSignatures
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [as 别名]
def __filterSignatures(self):
"""
Private method to filter the log entries.
"""
searchRxText = self.rxEdit.text()
filterTop = self.categoryCombo.currentText() == self.tr("Revision")
if filterTop and searchRxText.startswith("^"):
searchRx = QRegExp(
"^\s*{0}".format(searchRxText[1:]), Qt.CaseInsensitive)
else:
searchRx = QRegExp(searchRxText, Qt.CaseInsensitive)
for topIndex in range(self.signaturesList.topLevelItemCount()):
topLevelItem = self.signaturesList.topLevelItem(topIndex)
if filterTop:
topLevelItem.setHidden(
searchRx.indexIn(topLevelItem.text(0)) == -1)
else:
visibleChildren = topLevelItem.childCount()
for childIndex in range(topLevelItem.childCount()):
childItem = topLevelItem.child(childIndex)
if searchRx.indexIn(childItem.text(0)) == -1:
childItem.setHidden(True)
visibleChildren -= 1
else:
childItem.setHidden(False)
topLevelItem.setHidden(visibleChildren == 0)
示例2: run
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [as 别名]
def run(self):
"""Execute this rules in another thread to avoid blocking the ui."""
styles = {}
self.msleep(300)
block = self._highlighter.document().begin()
while block.blockNumber() != -1:
text = block.text()
formats = []
for expression, nth, char_format in self._highlighter.rules:
index = expression.indexIn(text, 0)
while index >= 0:
# We actually want the index of the nth match
index = expression.pos(nth)
length = len(expression.cap(nth))
formats.append((index, length, char_format))
index = expression.indexIn(text, index + length)
#Spaces
expression = QRegExp('\s+')
index = expression.indexIn(text, 0)
while index >= 0:
index = expression.pos(0)
length = len(expression.cap(0))
formats.append((index, length, STYLES['spaces']))
index = expression.indexIn(text, index + length)
styles[block.blockNumber()] = formats
block = block.next()# block = next(block)
self.highlightingDetected.emit(styles)
示例3: highlightBlock
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [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);
示例4: XmlSyntaxHighlighter
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [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: highlightBlock
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [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)
示例6: parseInDocRules
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [as 别名]
def parseInDocRules(self):
oldRules = self.inDocRules
self.inDocRules = []
t = self.thisDocument.toPlainText()
# Get all conf files
confs = []
lines = t.split("\n")
for l in lines:
r = QRegExp(r'^%!includeconf:\s*([^\s]*)\s*')
if r.indexIn(l) != -1:
confs.append(r.cap(1))
# Try to load conf files
for c in confs:
try:
import codecs
f = self.editor.fileWidget.file
d = QDir.cleanPath(QFileInfo(f).absoluteDir().absolutePath() + "/" + c)
file = codecs.open(d, 'r', "utf-8")
except:
print(("Error: cannot open {}.".format(c)))
continue
# We add the content to the current lines of the current document
lines += file.readlines() # lines.extend(file.readlines())
# b = self.thisDocument.firstBlock()
lastColor = ""
# while b.isValid():
for l in lines:
text = l # b.text()
r = QRegExp(r'^%!p[or][se]t?proc[^\s]*\s*:\s*(\'[^\']*\'|\"[^\"]*\")\s*(\'[^\']*\'|\"[^\"]*\")')
if r.indexIn(text) != -1:
rule = r.cap(1)[1:-1]
# Check if there was a color-comment above that post/preproc bloc
if lastColor:
self.inDocRules.append((str(rule), lastColor))
# Check if previous block is a comment like it should
else:
previousText = lines[lines.indexOf(l) - 1] # b.previous().text()
r = QRegExp(r'^%.*\s\((.*)\)')
if r.indexIn(previousText) != -1:
lastColor = r.cap(1)
self.inDocRules.append((str(rule), lastColor))
else:
lastColor = ""
# b = b.next()
if oldRules != self.inDocRules:
# Rules have changed, we need to rehighlight
# print("Rules have changed.", len(self.inDocRules))
# self.rehighlight() # Doesn't work (seg fault), why?
pass
示例7: __scriptDownloaded
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [as 别名]
def __scriptDownloaded(self):
"""
Private slot to handle the finished download of a script.
"""
if self.sender() != self.__reply:
self.finished.emit()
return
response = bytes(self.__reply.readAll()).decode()
if self.__reply.error() == QNetworkReply.NoError and \
"// ==UserScript==" in response:
from Helpviewer import HelpUtilities
filePath = os.path.join(
self.__manager.scriptsDirectory(),
HelpUtilities.getFileNameFromUrl(self.__reply.url()))
self.__fileName = HelpUtilities.ensureUniqueFilename(filePath)
try:
f = open(self.__fileName, "w", encoding="utf-8")
except (IOError, OSError) as err:
E5MessageBox.critical(
None,
self.tr("GreaseMonkey Download"),
self.tr(
"""<p>The file <b>{0}</b> could not be opened"""
""" for writing.<br/>Reason: {1}</p>""").format(
self.__fileName, str(err)))
self.finished.emit()
return
f.write(response)
f.close()
settings = QSettings(
os.path.join(self.__manager.requireScriptsDirectory(),
"requires.ini"),
QSettings.IniFormat)
settings.beginGroup("Files")
rx = QRegExp("@require(.*)\\n")
rx.setMinimal(True)
rx.indexIn(response)
for i in range(1, rx.captureCount() + 1):
url = rx.cap(i).strip()
if url and not settings.contains(url):
self.__requireUrls.append(QUrl(url))
self.__reply.deleteLater()
self.__reply = None
self.__downloadRequires()
示例8: lessThan
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [as 别名]
def lessThan(self, left, right):
leftData = self.sourceModel().data(left)
rightData = self.sourceModel().data(right)
if not isinstance(leftData, QDate):
emailPattern = QRegExp("([\\w\\.]*@[\\w\\.]*)")
if left.column() == 1 and emailPattern.indexIn(leftData) != -1:
leftData = emailPattern.cap(1)
if right.column() == 1 and emailPattern.indexIn(rightData) != -1:
rightData = emailPattern.cap(1)
return leftData < rightData
示例9: refresh
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [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)
示例10: findIndex
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [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
示例11: highlightBlock
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [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)
示例12: HostnameMatcher
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [as 别名]
class HostnameMatcher(object):
"""
Class implementing a matcher for host names.
"""
def __init__(self, pattern):
"""
Constructor
@param pattern pattern to be matched against
@type str
"""
self.__regExp = None
self.setPattern(pattern)
def setPattern(self, pattern):
"""
Public method to set the match pattern.
@param pattern pattern to be matched against
"""
self.__pattern = pattern
if "?" in pattern or "*" in pattern:
regexp = "^.*{0}.*$".format(pattern.replace(".", "\\.").replace("*", ".*").replace("?", "."))
self.__regExp = QRegExp(regexp, Qt.CaseInsensitive)
def pattern(self):
"""
Public method to get the match pattern.
@return match pattern
@rtype str
"""
return self.__pattern
def match(self, host):
"""
Public method to test the given string.
@param host host name to be matched
@type str
@return flag indicating a successful match
@rtype bool
"""
if self.__regExp is None:
return self.__pattern in host
return self.__regExp.indexIn(host) > -1
示例13: __init__
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [as 别名]
def __init__(self, mainWindow, parent = None):
super().__init__(parent)
self.mMainWindow = mainWindow
self.setRootIsDecorated(False)
self.setHeaderHidden(True)
self.setItemsExpandable(False)
self.setUniformRowHeights(True)
self.setDragEnabled(True)
self.setDefaultDropAction(Qt.MoveAction)
prefs = preferences.Preferences.instance()
prefs.mapsDirectoryChanged.connect(self.onMapsDirectoryChanged)
mapsDir = QDir(prefs.mapsDirectory())
if (not mapsDir.exists()):
mapsDir.setPath(QDir.currentPath())
self.mFSModel = FileSystemModel(self)
self.mFSModel.setRootPath(mapsDir.absolutePath())
nameFilters = QStringList("*.tmx")
# The file system model name filters are plain, whereas the plugins expose
# a filter as part of the file description
filterFinder = QRegExp("\\((\\*\\.[^\\)\\s]*)")
for format in PluginManager.objects(MapFormat):
if not (format.capabilities() & MapFormat.Read):
continue
filter = format.nameFilter()
if (filterFinder.indexIn(filter) != -1):
nameFilters.append(filterFinder.cap(1))
self.mFSModel.setFilter(QDir.AllDirs | QDir.Files | QDir.NoDot)
self.mFSModel.setNameFilters(nameFilters)
self.mFSModel.setNameFilterDisables(False) # hide filtered files
self.setModel(self.mFSModel)
headerView = self.header()
headerView.hideSection(1) # Size column
headerView.hideSection(2)
headerView.hideSection(3)
self.setRootIndex(self.mFSModel.index(mapsDir.absolutePath()))
self.header().setStretchLastSection(False)
self.header().setSectionResizeMode(0, QHeaderView.Stretch)
self.activated.connect(self.onActivated)
self.mMainWindow = None
self.mFSModel = None
示例14: findAllIndices
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [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
示例15: __filterLogs
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import indexIn [as 别名]
def __filterLogs(self):
"""
Private method to filter the log entries.
"""
if self.__filterLogsEnabled:
from_ = self.fromDate.date().toString("yyyy-MM-dd")
to_ = self.toDate.date().addDays(1).toString("yyyy-MM-dd")
txt = self.fieldCombo.currentText()
if txt == self.tr("Author"):
fieldIndex = 1
searchRx = QRegExp(self.rxEdit.text(), Qt.CaseInsensitive)
elif txt == self.tr("Revision"):
fieldIndex = 0
txt = self.rxEdit.text()
if txt.startswith("^"):
searchRx = QRegExp(
"^\s*{0}".format(txt[1:]), Qt.CaseInsensitive)
else:
searchRx = QRegExp(txt, Qt.CaseInsensitive)
else:
fieldIndex = 3
searchRx = QRegExp(self.rxEdit.text(), Qt.CaseInsensitive)
currentItem = self.logTree.currentItem()
for topIndex in range(self.logTree.topLevelItemCount()):
topItem = self.logTree.topLevelItem(topIndex)
if topItem.text(2) <= to_ and topItem.text(2) >= from_ and \
searchRx.indexIn(topItem.text(fieldIndex)) > -1:
topItem.setHidden(False)
if topItem is currentItem:
self.on_logTree_currentItemChanged(topItem, None)
else:
topItem.setHidden(True)
if topItem is currentItem:
self.messageEdit.clear()
self.filesTree.clear()