本文整理汇总了Python中PyQt5.QtCore.QRegExp.cap方法的典型用法代码示例。如果您正苦于以下问题:Python QRegExp.cap方法的具体用法?Python QRegExp.cap怎么用?Python QRegExp.cap使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtCore.QRegExp
的用法示例。
在下文中一共展示了QRegExp.cap方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: highlightBlock
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [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: parseInDocRules
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [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
示例3: lessThan
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [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
示例4: findCodecs
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [as 别名]
def findCodecs(self):
codecMap = []
iso8859RegExp = QRegExp('ISO[- ]8859-([0-9]+).*')
for mib in QTextCodec.availableMibs():
codec = QTextCodec.codecForMib(mib)
sortKey = codec_name(codec).upper()
rank = 0
if sortKey.startswith('UTF-8'):
rank = 1
elif sortKey.startswith('UTF-16'):
rank = 2
elif iso8859RegExp.exactMatch(sortKey):
if len(iso8859RegExp.cap(1)) == 1:
rank = 3
else:
rank = 4
else:
rank = 5
codecMap.append((str(rank) + sortKey, codec))
codecMap.sort()
self.codecs = [item[-1] for item in codecMap]
示例5: refresh
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [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)
示例6: run
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [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)
示例7: valueFromText
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [as 别名]
def valueFromText(text):
regExp = QRegExp("(\\d+)(\\s*[xx]\\s*\\d+)?")
if regExp.exactMatch(text):
return int(regExp.cap(1))
else:
return 0
示例8: getSize
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [as 别名]
def getSize(self):
text, ok = QInputDialog.getText(self, "Grabber",
"Enter pixmap size:", QLineEdit.Normal,
"%d x %d" % (self.glWidget.width(), self.glWidget.height()))
if not ok:
return QSize()
regExp = QRegExp(r'([0-9]+) *x *([0-9]+)')
if regExp.exactMatch(text):
width = int(regExp.cap(1))
height = int(regExp.cap(2))
if width > 0 and width < 2048 and height > 0 and height < 2048:
return QSize(width, height)
return self.glWidget.size()
示例9: __scriptDownloaded
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [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()
示例10: __init__
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [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
示例11: __init__
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [as 别名]
def __init__(self, parent=None):
super(StyleSheetEditor, self).__init__(parent)
self.ui = Ui_StyleSheetEditor()
self.ui.setupUi(self)
regExp = QRegExp(r'.(.*)\+?Style')
defaultStyle = QApplication.style().metaObject().className()
if regExp.exactMatch(defaultStyle):
defaultStyle = regExp.cap(1)
self.ui.styleCombo.addItems(QStyleFactory.keys())
self.ui.styleCombo.setCurrentIndex(
self.ui.styleCombo.findText(defaultStyle, Qt.MatchContains))
self.ui.styleSheetCombo.setCurrentIndex(
self.ui.styleSheetCombo.findText('Coffee'))
self.loadStyleSheet('Coffee')
示例12: SvnRepoBrowserDialog
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [as 别名]
#.........这里部分代码省略.........
self.process.waitForFinished(3000)
self.inputGroup.setEnabled(False)
self.inputGroup.hide()
self.__resizeColumns()
self.__resort()
QApplication.restoreOverrideCursor()
def __procFinished(self, exitCode, exitStatus):
"""
Private slot connected to the finished signal.
@param exitCode exit code of the process (integer)
@param exitStatus exit status of the process (QProcess.ExitStatus)
"""
self.__finish()
def __readStdout(self):
"""
Private slot to handle the readyReadStandardOutput signal.
It reads the output of the process, formats it and inserts it into
the contents pane.
"""
if self.process is not None:
self.process.setReadChannel(QProcess.StandardOutput)
while self.process.canReadLine():
s = str(self.process.readLine(),
Preferences.getSystem("IOEncoding"),
'replace')
if self.__rx_dir.exactMatch(s):
revision = self.__rx_dir.cap(1)
author = self.__rx_dir.cap(2)
date = self.__rx_dir.cap(3)
name = self.__rx_dir.cap(4).strip()
if name.endswith("/"):
name = name[:-1]
size = ""
nodekind = "dir"
if name == ".":
continue
elif self.__rx_file.exactMatch(s):
revision = self.__rx_file.cap(1)
author = self.__rx_file.cap(2)
size = self.__rx_file.cap(3)
date = self.__rx_file.cap(4)
name = self.__rx_file.cap(5).strip()
nodekind = "file"
else:
continue
url = "{0}/{1}".format(self.repoUrl, name)
self.__generateItem(
name, revision, author, size, date, nodekind, url)
def __readStderr(self):
"""
Private slot to handle the readyReadStandardError signal.
It reads the error output of the process and inserts it into the
error pane.
"""
if self.process is not None:
s = str(self.process.readAllStandardError(),
Preferences.getSystem("IOEncoding"),
示例13: __init__
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [as 别名]
def __init__(self, vcs, tagsList, branchesList, path, parent=None):
"""
Constructor
@param vcs reference to the vcs object
@param tagsList list of tags (list of strings)
@param branchesList list of branches (list of strings)
@param path pathname to determine the repository URL from (string)
@param parent parent widget of the dialog (QWidget)
"""
super(SvnUrlSelectionDialog, self).__init__(parent)
self.setupUi(self)
if not hasattr(pysvn.Client(), 'diff_summarize'):
self.summaryCheckBox.setEnabled(False)
self.summaryCheckBox.setChecked(False)
self.vcs = vcs
self.tagsList = tagsList
self.branchesList = branchesList
self.typeCombo1.addItems(["trunk/", "tags/", "branches/"])
self.typeCombo2.addItems(["trunk/", "tags/", "branches/"])
reposURL = self.vcs.svnGetReposName(path)
if reposURL is None:
E5MessageBox.critical(
self,
self.tr("Subversion Error"),
self.tr(
"""The URL of the project repository could not be"""
""" retrieved from the working copy. The operation will"""
""" be aborted"""))
self.reject()
return
if self.vcs.otherData["standardLayout"]:
# determine the base path of the project in the repository
rx_base = QRegExp('(.+/)(trunk|tags|branches).*')
if not rx_base.exactMatch(reposURL):
E5MessageBox.critical(
self,
self.tr("Subversion Error"),
self.tr(
"""The URL of the project repository has an"""
""" invalid format. The operation will"""
""" be aborted"""))
self.reject()
return
reposRoot = rx_base.cap(1)
self.repoRootLabel1.setText(reposRoot)
self.repoRootLabel2.setText(reposRoot)
else:
project = e5App().getObject('Project')
if Utilities.normcasepath(path) != \
Utilities.normcasepath(project.getProjectPath()):
path = project.getRelativePath(path)
reposURL = reposURL.replace(path, '')
self.repoRootLabel1.hide()
self.typeCombo1.hide()
self.labelCombo1.addItems([reposURL] + sorted(self.vcs.tagsList))
self.labelCombo1.setEnabled(True)
self.repoRootLabel2.hide()
self.typeCombo2.hide()
self.labelCombo2.addItems([reposURL] + sorted(self.vcs.tagsList))
self.labelCombo2.setEnabled(True)
msh = self.minimumSizeHint()
self.resize(max(self.width(), msh.width()), msh.height())
示例14: SvnStatusMonitorThread
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [as 别名]
class SvnStatusMonitorThread(VcsStatusMonitorThread):
"""
Class implementing the VCS status monitor thread class for Subversion.
"""
def __init__(self, interval, project, vcs, parent=None):
"""
Constructor
@param interval new interval in seconds (integer)
@param project reference to the project object (Project)
@param vcs reference to the version control object
@param parent reference to the parent object (QObject)
"""
VcsStatusMonitorThread.__init__(self, interval, project, vcs, parent)
self.__ioEncoding = Preferences.getSystem("IOEncoding")
self.rx_status1 = \
QRegExp('(.{8,9})\\s+([0-9-]+)\\s+(.+)\\s*')
self.rx_status2 = QRegExp(
'(.{8,9})\\s+([0-9-]+)\\s+([0-9?]+)\\s+(\\S+)\\s+(.+)\\s*')
def _performMonitor(self):
"""
Protected method implementing the monitoring action.
This method populates the statusList member variable
with a list of strings giving the status in the first column and the
path relative to the project directory starting with the third column.
The allowed status flags are:
<ul>
<li>"A" path was added but not yet comitted</li>
<li>"M" path has local changes</li>
<li>"O" path was removed</li>
<li>"R" path was deleted and then re-added</li>
<li>"U" path needs an update</li>
<li>"Z" path contains a conflict</li>
<li>" " path is back at normal</li>
</ul>
@return tuple of flag indicating successful operation (boolean) and
a status message in case of non successful operation (string)
"""
self.shouldUpdate = False
process = QProcess()
args = []
args.append('status')
if not Preferences.getVCS("MonitorLocalStatus"):
args.append('--show-updates')
args.append('--non-interactive')
args.append('.')
process.setWorkingDirectory(self.projectDir)
process.start('svn', args)
procStarted = process.waitForStarted(5000)
if procStarted:
finished = process.waitForFinished(300000)
if finished and process.exitCode() == 0:
output = str(process.readAllStandardOutput(),
self.__ioEncoding, 'replace')
states = {}
for line in output.splitlines():
if self.rx_status1.exactMatch(line):
flags = self.rx_status1.cap(1)
path = self.rx_status1.cap(3).strip()
elif self.rx_status2.exactMatch(line):
flags = self.rx_status2.cap(1)
path = self.rx_status2.cap(5).strip()
else:
continue
if flags[0] in "ACDMR" or \
(flags[0] == " " and flags[-1] == "*"):
if flags[-1] == "*":
status = "U"
else:
status = flags[0]
if status == "C":
status = "Z" # give it highest priority
elif status == "D":
status = "O"
if status == "U":
self.shouldUpdate = True
name = path
states[name] = status
try:
if self.reportedStates[name] != status:
self.statusList.append(
"{0} {1}".format(status, name))
except KeyError:
self.statusList.append(
"{0} {1}".format(status, name))
for name in list(self.reportedStates.keys()):
if name not in states:
self.statusList.append(" {0}".format(name))
self.reportedStates = states
return True, self.tr(
"Subversion status checked successfully (using svn)")
else:
process.kill()
process.waitForFinished()
#.........这里部分代码省略.........
示例15: SvnStatusDialog
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import cap [as 别名]
#.........这里部分代码省略.........
@param button button that was clicked (QAbstractButton)
"""
if button == self.buttonBox.button(QDialogButtonBox.Close):
self.close()
elif button == self.buttonBox.button(QDialogButtonBox.Cancel):
self.__finish()
elif button == self.refreshButton:
self.on_refreshButton_clicked()
def __procFinished(self, exitCode, exitStatus):
"""
Private slot connected to the finished signal.
@param exitCode exit code of the process (integer)
@param exitStatus exit status of the process (QProcess.ExitStatus)
"""
self.__finish()
def __readStdout(self):
"""
Private slot to handle the readyReadStandardOutput signal.
It reads the output of the process, formats it and inserts it into
the contents pane.
"""
if self.process is not None:
self.process.setReadChannel(QProcess.StandardOutput)
while self.process.canReadLine():
s = str(self.process.readLine(),
Preferences.getSystem("IOEncoding"),
'replace')
if self.rx_status.exactMatch(s):
flags = self.rx_status.cap(1)
rev = self.rx_status.cap(2)
change = self.rx_status.cap(3)
author = self.rx_status.cap(4)
path = self.rx_status.cap(5).strip()
self.__generateItem(flags[0], flags[1], flags[2], flags[3],
flags[4], flags[5], flags[-1], rev,
change, author, path)
elif self.rx_status2.exactMatch(s):
flags = self.rx_status2.cap(1)
path = self.rx_status2.cap(2).strip()
self.__generateItem(flags[0], flags[1], flags[2], flags[3],
flags[4], flags[5], flags[-1], "", "",
"", path)
elif self.rx_changelist.exactMatch(s):
self.currentChangelist = self.rx_changelist.cap(1)
self.changelistFound = True
def __readStderr(self):
"""
Private slot to handle the readyReadStandardError signal.
It reads the error output of the process and inserts it into the
error pane.
"""
if self.process is not None:
self.errorGroup.show()
s = str(self.process.readAllStandardError(),
Preferences.getSystem("IOEncoding"),
'replace')
self.errors.insertPlainText(s)