本文整理汇总了Python中PyQt5.QtCore.QRegExp.exactMatch方法的典型用法代码示例。如果您正苦于以下问题:Python QRegExp.exactMatch方法的具体用法?Python QRegExp.exactMatch怎么用?Python QRegExp.exactMatch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtCore.QRegExp
的用法示例。
在下文中一共展示了QRegExp.exactMatch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: data_changed
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [as 别名]
def data_changed(self, index1, index2, roles):
if index1.column() in (1, 3):
regexp1 = QRegExp("^-?\d+(\.\d+)?$")
regexp2 = QRegExp("^\d+$")
if len(str(index1.data())) == 0:
QMessageBox.critical(None,
"Invalid data",
"Field cannot be empty.",
QMessageBox.Ok)
self.model.revertRow(index1.row())
elif len(str(index1.data())) != len(str(index1.data()).strip()):
QMessageBox.critical(None,
"Invalid data",
"Unwanted whitespace character.",
QMessageBox.Ok)
self.model.revertRow(index1.row())
elif index1.column() == 1 and not regexp1.exactMatch(str(index1.data())):
QMessageBox.critical(None,
"Invalid data",
"Field must be numeric.",
QMessageBox.Ok)
self.model.revertRow(index1.row())
elif index1.column() == 3 and not regexp2.exactMatch(str(index1.data())):
QMessageBox.critical(None,
"Invalid data",
"Field must be numeric.",
QMessageBox.Ok)
self.model.revertRow(index1.row())
示例2: valueFromText
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [as 别名]
def valueFromText(text):
regExp = QRegExp("(\\d+)(\\s*[xx]\\s*\\d+)?")
if regExp.exactMatch(text):
return int(regExp.cap(1))
else:
return 0
示例3: setData
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [as 别名]
def setData(self, index, value, role):
"""
This function is called when a content in a row is edited by the user.
:param index: Current selected index.
:param value: New value from user
:param role:
:return:
"""
if not index.isValid():
return None
row = index.row()
col = index.column()
if role == Qt.EditRole:
if col == 1:
index_sibling = index.sibling(row, col-1)
dparameter = super(DParameterTreeModel, self).data(index_sibling, Qt.UserRole)
if dparameter.regex is not None:
rx = QRegExp(dparameter.regex)
if rx.exactMatch(value):
dparameter.value = value
self.dataChanged.emit(index_sibling, index_sibling)
else:
dparameter.value = value
self.dataChanged.emit(index_sibling, index_sibling)
return True
return False
示例4: validate
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [as 别名]
def validate(self, inpt: str, pos: int):
if self.suffix().upper() in ("", "K", "M", "G"):
rx = QRegExp("^(-?[0-9]+)[.]?[0-9]*[kKmMgG]?$")
else:
rx = QRegExp("^(-?[0-9]+)[.]?[0-9]*[{}]?$".format(self.suffix()))
result = QValidator.Acceptable if rx.exactMatch(inpt.replace(",", ".")) else QValidator.Invalid
return result, inpt, pos
示例5: findCodecs
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [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]
示例6: HexValidator
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [as 别名]
class HexValidator(QValidator):
def __init__(self, max_bytes=-1):
super().__init__()
self.max_bytes = max_bytes
if max_bytes == 0:
self.re_acceptable = QRegExp('')
self.re_intermediate = QRegExp('')
elif max_bytes > 0:
self.re_acceptable = QRegExp('([0-9A-Fa-f]{2} ){0,%d}[0-9A-Fa-f]{2}' % (max_bytes - 1))
self.re_intermediate = QRegExp('[ ]*|([ ]*[0-9A-Fa-f][ ]*){1,%d}' % (max_bytes * 2))
else:
self.re_acceptable = QRegExp('([0-9A-Fa-f]{2} )*[0-9A-Fa-f]{2}')
self.re_intermediate = QRegExp('[ ]*|([ ]*[0-9A-Fa-f][ ]*)+')
def validate(self, _input, _pos):
_input = _input.upper()
if self.re_acceptable.exactMatch(_input):
return QValidator.Acceptable, _input, _pos
elif self.re_intermediate.exactMatch(_input):
return QValidator.Intermediate, _input, _pos
else:
return QValidator.Invalid, _input, _pos
def fixup(self, _input):
s = ''
n = self.max_bytes * 2
for i, c in enumerate(_input.replace(' ', '').upper()):
if n == 0:
break
if i % 2 == 0:
s += ' '
s += c
n -= 1
s = s.strip()
if len(s.replace(' ', '')) % 2 == 1:
s = s[:-1] + '0' + s[-1:]
return s
示例7: mark_visibility_by_name
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [as 别名]
def mark_visibility_by_name(self, value):
all_items_are_hidden = True
for row in range(self.rowCount()):
treeItem = self.child(row)
regex = QRegExp(value, Qt.CaseInsensitive, QRegExp.Wildcard)
if regex.exactMatch(treeItem.name):
treeItem.visible = True
all_items_are_hidden = False
else:
treeItem.visible = False
self.visible = not all_items_are_hidden
示例8: getSize
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [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: __init__
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [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')
示例10: TaskFilter
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [as 别名]
#.........这里部分代码省略.........
"""
if not filter:
self.summaryFilter = None
else:
self.summaryFilter = QRegExp(filter)
def setFileNameFilter(self, filter):
"""
Public method to set the filename filter.
@param filter a wildcard expression for the filename filter
to set (string) or None
"""
if not filter:
self.filenameFilter = None
else:
self.filenameFilter = QRegExp(filter)
self.filenameFilter.setPatternSyntax(QRegExp.Wildcard)
def setTypeFilter(self, taskType):
"""
Public method to set the type filter.
@param taskType type of the task (one of Task.TypeNone, Task.TypeFixme,
Task.TypeTodo, Task.TypeWarning, Task.TypeNote)
"""
self.typeFilter = taskType
def setScopeFilter(self, scope):
"""
Public method to set the scope filter.
@param scope flag indicating a project task (boolean) or None
"""
self.scopeFilter = scope
def setStatusFilter(self, status):
"""
Public method to set the status filter.
@param status flag indicating a completed task (boolean) or None
"""
self.statusFilter = status
def setPrioritiesFilter(self, priorities):
"""
Public method to set the priorities filter.
@param priorities list of task priorities (list of integer) or None
"""
self.prioritiesFilter = priorities
def hasActiveFilter(self):
"""
Public method to check for active filters.
@return flag indicating an active filter was found (boolean)
"""
return self.summaryFilter is not None or \
self.filenameFilter is not None or \
self.typeFilter != Task.TypeNone or \
self.scopeFilter is not None or \
self.statusFilter is not None or \
self.prioritiesFilter is not None
def showTask(self, task):
"""
Public method to check, if a task should be shown.
@param task reference to the task object to check (Task)
@return flag indicating whether the task should be shown (boolean)
"""
if not self.active:
return True
if self.summaryFilter and \
self.summaryFilter.indexIn(task.summary) == -1:
return False
if self.filenameFilter and \
not self.filenameFilter.exactMatch(task.filename):
return False
if self.typeFilter != Task.TypeNone and \
self.typeFilter != task.taskType:
return False
if self.scopeFilter is not None and \
self.scopeFilter != task._isProjectTask:
return False
if self.statusFilter is not None and \
self.statusFilter != task.completed:
return False
if self.prioritiesFilter is not None and \
task.priority not in self.prioritiesFilter:
return False
return True
示例11: SvnLogDialog
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [as 别名]
#.........这里部分代码省略.........
self.activateWindow()
self.raise_()
args.append(self.fname)
self.process.setWorkingDirectory(self.dname)
self.process.start('svn', args)
procStarted = self.process.waitForStarted(5000)
if not procStarted:
self.inputGroup.setEnabled(False)
E5MessageBox.critical(
self,
self.tr('Process Generation Error'),
self.tr(
'The process {0} could not be started. '
'Ensure, that it is in the search path.'
).format('svn'))
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.inputGroup.setEnabled(False)
self.inputGroup.hide()
self.contents.clear()
lvers = 1
for s in self.buf:
rev_match = False
if self.rx_rev.exactMatch(s):
ver = self.rx_rev.cap(1)
author = self.rx_rev.cap(2)
date = self.rx_rev.cap(3)
# number of lines is ignored
rev_match = True
elif self.rx_rev2.exactMatch(s):
ver = self.rx_rev2.cap(1)
author = self.rx_rev2.cap(2)
date = self.rx_rev2.cap(3)
# number of lines is ignored
rev_match = True
if rev_match:
dstr = '<b>{0} {1}</b>'.format(self.revString, ver)
try:
lv = self.revisions[lvers]
lvers += 1
url = QUrl()
url.setScheme("file")
url.setPath(self.filename)
if qVersion() >= "5.0.0":
query = lv + '_' + ver
url.setQuery(query)
else:
query = QByteArray()
query.append(lv).append('_').append(ver)
url.setEncodedQuery(query)
dstr += ' [<a href="{0}" name="{1}">{2}</a>]'.format(
url.toString(), query,
self.tr('diff to {0}').format(lv),
)
except IndexError:
示例12: CallTraceViewer
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [as 别名]
#.........这里部分代码省略.........
try:
f = open(fname, "w", encoding="utf-8")
itm = self.callTrace.topLevelItem(0)
while itm is not None:
isCall = itm.data(0, Qt.UserRole)
if isCall:
call = "->"
else:
call = "<-"
f.write("{0} {1} || {2}\n".format(
call,
itm.text(1), itm.text(2)))
itm = self.callTrace.itemBelow(itm)
f.close()
except IOError as err:
E5MessageBox.critical(
self,
self.tr("Error saving Call Trace Info"),
self.tr("""<p>The call trace info could not"""
""" be written to <b>{0}</b></p>"""
"""<p>Reason: {1}</p>""")
.format(fname, str(err)))
@pyqtSlot(QTreeWidgetItem, int)
def on_callTrace_itemDoubleClicked(self, item, column):
"""
Private slot to open the double clicked file in an editor.
@param item reference to the double clicked item (QTreeWidgetItem)
@param column column that was double clicked (integer)
"""
if item is not None and column > 0:
columnStr = item.text(column)
if self.__entryRe.exactMatch(columnStr.strip()):
filename, lineno, func = self.__entryRe.capturedTexts()[1:]
try:
lineno = int(lineno)
except ValueError:
# do nothing, if the line info is not an integer
return
if self.__projectMode:
filename = self.__project.getAbsolutePath(filename)
self.sourceFile.emit(filename, lineno)
def clear(self):
"""
Public slot to clear the call trace info.
"""
self.callTrace.clear()
self.__callStack = []
def setProjectMode(self, enabled):
"""
Public slot to set the call trace viewer to project mode.
In project mode the call trace info is shown with project relative
path names.
@param enabled flag indicating to enable the project mode (boolean)
"""
self.__projectMode = enabled
if enabled and self.__project is None:
self.__project = e5App().getObject("Project")
def __addCallTraceInfo(self, isCall, fromFile, fromLine, fromFunction,
toFile, toLine, toFunction):
示例13: start
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [as 别名]
def start(self, path, tags=True):
"""
Public slot to start the svn status command.
@param path name of directory to be listed (string)
@param tags flag indicating a list of tags is requested
(False = branches, True = tags)
@return flag indicating success (boolean)
"""
self.errorGroup.hide()
self.tagList.clear()
if not tags:
self.setWindowTitle(self.tr("Subversion Branches List"))
self.activateWindow()
QApplication.processEvents()
dname, fname = self.vcs.splitPath(path)
reposURL = self.vcs.svnGetReposName(dname)
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 list operation"""
""" will be aborted"""))
self.close()
return False
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 list operation will"""
""" be aborted"""))
return False
reposRoot = rx_base.cap(1)
if tags:
path = "{0}/tags".format(reposRoot)
else:
path = "{0}/branches".format(reposRoot)
else:
reposPath, ok = QInputDialog.getText(
self,
self.tr("Subversion List"),
self.tr("Enter the repository URL containing the"
" tags or branches"),
QLineEdit.Normal,
self.vcs.svnNormalizeURL(reposURL))
if not ok:
self.close()
return False
if not reposPath:
E5MessageBox.critical(
self,
self.tr("Subversion List"),
self.tr(
"""The repository URL is empty. Aborting..."""))
self.close()
return False
path = reposPath
locker = QMutexLocker(self.vcs.vcsExecutionMutex)
self.tagsList = []
cwd = os.getcwd()
os.chdir(dname)
try:
entries = self.client.list(path, recurse=False)
# dirent, lock already unicode in Python 2
for dirent, lock in entries:
if dirent["path"] != path:
name = dirent["path"].replace(path + '/', "")
self.__generateItem(dirent["created_rev"].number,
dirent["last_author"],
formatTime(dirent["time"]),
name)
if self.vcs.otherData["standardLayout"]:
self.tagsList.append(name)
else:
self.tagsList.append(path + '/' + name)
if self._clientCancelCallback():
break
res = True
except pysvn.ClientError as e:
self.__showError(e.args[0])
res = False
except AttributeError:
self.__showError(
self.tr("The installed version of PySvn should be"
" 1.4.0 or better."))
#.........这里部分代码省略.........
示例14: SvnRepoBrowserDialog
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [as 别名]
#.........这里部分代码省略.........
QTimer.singleShot(2000, self.process.kill)
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(),
示例15: CompleterRuby
# 需要导入模块: from PyQt5.QtCore import QRegExp [as 别名]
# 或者: from PyQt5.QtCore.QRegExp import exactMatch [as 别名]
class CompleterRuby(CompleterBase):
"""
Class implementing typing completer for Ruby.
"""
def __init__(self, editor, parent=None):
"""
Constructor
@param editor reference to the editor object (QScintilla.Editor)
@param parent reference to the parent object (QObject)
"""
CompleterBase.__init__(self, editor, parent)
self.__beginRX = QRegExp(r"""^=begin """)
self.__beginNlRX = QRegExp(r"""^=begin\r?\n""")
self.__hereRX = QRegExp(r"""<<-?['"]?(\w*)['"]?\r?\n""")
self.readSettings()
def readSettings(self):
"""
Public slot called to reread the configuration parameters.
"""
self.setEnabled(Preferences.getEditorTyping("Ruby/EnabledTypingAids"))
self.__insertClosingBrace = Preferences.getEditorTyping("Ruby/InsertClosingBrace")
self.__indentBrace = Preferences.getEditorTyping("Ruby/IndentBrace")
self.__skipBrace = Preferences.getEditorTyping("Ruby/SkipBrace")
self.__insertQuote = Preferences.getEditorTyping("Ruby/InsertQuote")
self.__insertBlank = Preferences.getEditorTyping("Ruby/InsertBlank")
self.__insertHereDoc = Preferences.getEditorTyping("Ruby/InsertHereDoc")
self.__insertInlineDoc = Preferences.getEditorTyping("Ruby/InsertInlineDoc")
def charAdded(self, charNumber):
"""
Public slot called to handle the user entering a character.
@param charNumber value of the character entered (integer)
"""
char = chr(charNumber)
if char not in ["(", ")", "{", "}", "[", "]", ",", "'", '"', "\n", " "]:
return # take the short route
line, col = self.editor.getCursorPosition()
if (
self.__inComment(line, col)
or self.__inDoubleQuotedString()
or self.__inSingleQuotedString()
or self.__inHereDocument()
or self.__inInlineDocument()
):
return
# open parenthesis
# insert closing parenthesis and self
if char == "(":
txt = self.editor.text(line)[:col]
if self.__insertClosingBrace:
self.editor.insert(")")
# closing parenthesis
# skip matching closing parenthesis
elif char in [")", "}", "]"]:
txt = self.editor.text(line)
if col < len(txt) and char == txt[col]:
if self.__skipBrace:
self.editor.setSelection(line, col, line, col + 1)
self.editor.removeSelectedText()
# space
# complete inline documentation
elif char == " ":
txt = self.editor.text(line)[:col]
if self.__insertInlineDoc and self.__beginRX.exactMatch(txt):
self.editor.insert("=end")
# comma
# insert blank
elif char == ",":
if self.__insertBlank:
self.editor.insert(" ")
self.editor.setCursorPosition(line, col + 1)
# open curly brace
# insert closing brace
elif char == "{":
if self.__insertClosingBrace:
self.editor.insert("}")
# open bracket
# insert closing bracket
elif char == "[":
if self.__insertClosingBrace:
self.editor.insert("]")
# double quote
# insert double quote
elif char == '"':
if self.__insertQuote:
#.........这里部分代码省略.........