当前位置: 首页>>代码示例>>Python>>正文


Python QtCore.QRegExp类代码示例

本文整理汇总了Python中PyQt4.QtCore.QRegExp的典型用法代码示例。如果您正苦于以下问题:Python QRegExp类的具体用法?Python QRegExp怎么用?Python QRegExp使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QRegExp类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: event

    def event(self, event):
        if event.type() == QEvent.KeyPress:

            if event.key() in (Qt.Key_Shift, Qt.Key_Control, Qt.Key_AltGr, Qt.Key_Alt):
                return True

            regex = QRegExp(self.keyWordREGEX, Qt.CaseInsensitive, QRegExp.RegExp)
            if regex.exactMatch(self.text()) and not (event.key() == Qt.Key_Backspace): # 16777219 is the backspace
            #if event.key() != Qt.Key_Backspace and event.key() != Qt.Key_Space:
                QLineEdit.event(self, event)
                self.getWords()
                if not len(self.completions):
                    return True
                if self.text() == "":
                    return True

                if len(self.partials) >= 1:
                    autocomplete = self.partials[0]
                    self.applyCompletion(autocomplete)
                    signalAttach = QString(autocomplete)
                    self.AutoComplete.emit(signalAttach)    #if autocomplete got a "@" in it, only the part, starting with "@..." will be sent
                    return True
                else:
                    signalAttach = QString('NONE')
                    self.AutoComplete.emit(signalAttach)
                    return True


            else:
                return QLineEdit.event(self, event)

        else:
            return QLineEdit.event(self, event)
开发者ID:Acer54,项目名称:onlinesearch,代码行数:33,代码来源:LineEdit_Autocompletion_V2.py

示例2: highlightBlock

    def highlightBlock(self, text):
        """Apply syntax highlighting to the given block of text."""
        for expression, nth, format in self.rules:
            index = expression.indexIn(text, 0)

            while index >= 0:
                # We actually want the index of the nth match
                index = expression.pos(nth)
                length = expression.cap(nth).length()
                self.setFormat(index, length, format)
                index = expression.indexIn(text, index + length)

        self.setCurrentBlockState(0)
        if not self.multi_start:
            # Do multi-line strings
            in_multiline = self.match_multiline(text, *self.tri_single)
            if not in_multiline:
                in_multiline = self.match_multiline(text, *self.tri_double)
        else:
            # Do multi-line comment
            self.comment_multiline(text, self.multi_end[0], *self.multi_start)

        #Spaces
        expression = QRegExp('\s+')
        index = expression.indexIn(text, 0)
        while index >= 0:
            index = expression.pos(0)
            length = expression.cap(0).length()
            self.setFormat(index, length, STYLES['spaces'])
            index = expression.indexIn(text, index + length)
开发者ID:Morfyo,项目名称:PYTHON,代码行数:30,代码来源:highlighter.py

示例3: run

    def run(self):
        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 = expression.cap(nth).length()

                    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 = expression.cap(0).length()
                formats.append((index, length, STYLES["spaces"]))
                index = expression.indexIn(text, index + length)

            self.styles[block.blockNumber()] = formats
            block = block.next()
开发者ID:netantho,项目名称:ninja-ide,代码行数:29,代码来源:highlighter.py

示例4: run

    def run(self):
        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 = expression.cap(nth).length()

                    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 = expression.cap(0).length()
                formats.append((index, length, STYLES['spaces']))
                index = expression.indexIn(text, index + length)

            styles[block.blockNumber()] = formats
            block = block.next()
        self.emit(SIGNAL("highlightingDetected(PyQt_PyObject)"), styles)
开发者ID:aguzubiaga,项目名称:ninja-ide,代码行数:31,代码来源:highlighter.py

示例5: popup

    def popup(self, pos=None, searchText=""):
        """
        Popup the menu at `pos` (in screen coordinates). 'Search' text field
        is initialized with `searchText` if provided.

        """
        if pos is None:
            pos = QPoint()

        self.__clearCurrentItems()

        self.__search.setText(searchText)
        patt = QRegExp("(^|\W)"+searchText)
        patt.setCaseSensitivity(False)
        self.__suggestPage.setFilterRegExp(patt)

        self.ensurePolished()

        if self.testAttribute(Qt.WA_Resized) and self.sizeGripEnabled():
            size = self.size()
        else:
            size = self.sizeHint()

        desktop = QApplication.desktop()
        screen_geom = desktop.availableGeometry(pos)

        # Adjust the size to fit inside the screen.
        if size.height() > screen_geom.height():
            size.setHeight(screen_geom.height())
        if size.width() > screen_geom.width():
            size.setWidth(screen_geom.width())

        geom = QRect(pos, size)

        if geom.top() < screen_geom.top():
            geom.setTop(screen_geom.top())

        if geom.left() < screen_geom.left():
            geom.setLeft(screen_geom.left())

        bottom_margin = screen_geom.bottom() - geom.bottom()
        right_margin = screen_geom.right() - geom.right()
        if bottom_margin < 0:
            # Falls over the bottom of the screen, move it up.
            geom.translate(0, bottom_margin)

        # TODO: right to left locale
        if right_margin < 0:
            # Falls over the right screen edge, move the menu to the
            # other side of pos.
            geom.translate(-size.width(), 0)

        self.setGeometry(geom)

        self.show()

        if searchText:
            self.setFocusProxy(self.__search)
        else:
            self.setFocusProxy(None)
开发者ID:675801717,项目名称:orange3,代码行数:60,代码来源:quickmenu.py

示例6: HoogleRunner

class HoogleRunner(plasmascript.Runner):
    def init(self):
        """
        Initialize and register with Plasma.
        """
        self.myIcon = QIcon(self.package().filePath("images", "lambda.svg"))
        self.regExp = QRegExp("^hoogle (.*)$")
        syntax = Plasma.RunnerSyntax("hoogle :q:", "Query hoogle for :q:")
        self.addSyntax(syntax)
 
    def match(self, context):
        """
        Add a match to the given `context` iff the query starts with 'hoogle'.
        """
        if context.isValid() and self.regExp.exactMatch(context.query()):
            term = self.regExp.cap(1)
            m = Plasma.QueryMatch(self.runner)
            m.setText("Query Hoogle for '%s'" % term)
            m.setType(Plasma.QueryMatch.ExactMatch)
            m.setIcon(self.myIcon)
            m.setData(term)
            context.addMatch(term, m)
 
    def run(self, context, match):
        """
        Have KDE open the query in the browser.
        """
        urlString = QString("http://www.haskell.org/hoogle/?hoogle=")
        # Apparently Hoogle doesn't like percent encoded URLs.
        # urlString.append(QUrl.toPercentEncoding(match.data().toString()))
        urlString.append(match.data().toString())
        QDesktopServices().openUrl(QUrl(urlString))
开发者ID:afwlehmann,项目名称:hoogle-runner,代码行数:32,代码来源:main.py

示例7: __init__

    def __init__(self, parent=None):
        super(PythonHighlighter, self).__init__(parent)

        self.initializeFormats()

        PythonHighlighter.Rules.append((QRegExp(
                "|".join([r"\b%s\b" % keyword for keyword in KEYWORDS])),
                "keyword"))
        PythonHighlighter.Rules.append((QRegExp(
                "|".join([r"\b%s\b" % builtin for builtin in BUILTINS])),
                "builtin"))
        PythonHighlighter.Rules.append((QRegExp(
                "|".join([r"\b%s\b" % constant
                for constant in CONSTANTS])), "constant"))
        PythonHighlighter.Rules.append((QRegExp(
                r"\b[+-]?[0-9]+[lL]?\b"
                r"|\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b"
                r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"),
                "number"))
        PythonHighlighter.Rules.append((QRegExp(
                r"\bPyQt4\b|\bQt?[A-Z][a-z]\w+\b"), "pyqt"))
        PythonHighlighter.Rules.append((QRegExp(r"\[email protected]\w+\b"),
                "decorator"))
        stringRe = QRegExp(r"""(?:'[^']*'|"[^"]*")""")
        stringRe.setMinimal(True)
        PythonHighlighter.Rules.append((stringRe, "string"))
        self.stringRe = QRegExp(r"""(:?"["]".*"["]"|'''.*''')""")
        self.stringRe.setMinimal(True)
        PythonHighlighter.Rules.append((self.stringRe, "string"))
        self.tripleSingleRe = QRegExp(r"""'''(?!")""")
        self.tripleDoubleRe = QRegExp(r'''"""(?!')''')
开发者ID:pombredanne,项目名称:toolz-1,代码行数:31,代码来源:miscFunc.py

示例8: data

 def data(self, arg, value, *args, **kwargs):
     ip_reg = QRegExp(IP_REG)
     if (isinstance(value, list) or isinstance(value, tuple) or isinstance(value, str) or isinstance(value, int)) \
             and not ip_reg.exactMatch(str(value)):
         return ArgDataUserID(arg, value, *args, **kwargs)
     else:
         return ArgDataIP(arg, value, *args, **kwargs)
开发者ID:maximerobin,项目名称:Ufwi,代码行数:7,代码来源:__init__.py

示例9: run

    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()
        self.emit(SIGNAL("highlightingDetected(PyQt_PyObject)"), styles)
开发者ID:daqing15,项目名称:ninja-ide,代码行数:32,代码来源:highlighter.py

示例10: pg_tables

def pg_tables(schema="public", exclude_lookups=False):
    """
    Returns all the tables in the given schema minus the default PostGIS tables.
    Views are also excluded. See separate function for retrieving views.
    """
    t = text("SELECT table_name FROM information_schema.tables WHERE table_schema = :tschema and table_type = :tbtype " \
             "ORDER BY table_name ASC")
    result = _execute(t,tschema = schema,tbtype = "BASE TABLE")
        
    pgTables = []
        
    for r in result:
        tableName = r["table_name"]
        
        #Remove default PostGIS tables
        tableIndex = getIndex(_postGISTables, tableName)
        if tableIndex == -1:
            if exclude_lookups:
                #Validate if table is a lookup table and if it is, then omit
                rx = QRegExp("check_*")
                rx.setPatternSyntax(QRegExp.Wildcard)
                
                if not rx.exactMatch(tableName):
                    pgTables.append(tableName)
                    
            else:
                pgTables.append(tableName)
            
    return pgTables
开发者ID:olivierdalang,项目名称:stdm,代码行数:29,代码来源:pg_utils.py

示例11: RegexHighlighter

class RegexHighlighter(QSyntaxHighlighter):
    def __init__(self, widget):
        QSyntaxHighlighter.__init__(self, widget)
        self.regex = None
        # create format type
        self.odd_format = QTextCharFormat()
        self.odd_format.setFontWeight(QFont.Bold)
        self.odd_format.setForeground(Qt.darkBlue)
        self.even_format = QTextCharFormat()
        self.even_format.setFontWeight(QFont.Bold)
        self.even_format.setForeground(Qt.darkMagenta)

    def set_regex(self, exp):
        self.regex = QRegExp(exp)

    def highlightBlock(self, text):
        if not self.regex:
            return
        matches = 0
        pos = self.regex.indexIn(text, 0)
        while (pos >= 0):
            length = self.regex.matchedLength()
            matches += 1
            if matches % 2 == 0:
                self.setFormat(pos, length, self.even_format)
            else:
                self.setFormat(pos, length, self.odd_format)
            # handle wildcard (*)
            if length == 0:
                pos += 1
            pos = self.regex.indexIn(text, pos + length)
开发者ID:benosment,项目名称:regex-tool-pyqt4,代码行数:31,代码来源:regexhighlighter.py

示例12: fillInAvailableTools

    def fillInAvailableTools(self):

        # Operations on the selected item
        choices = {}

        # Classification for the selected item
        classification = ""

        if self.model.isDir(self.currentIndex):
            regex = QRegExp("\\d{4}") # match directory names with four digits
            name = self.model.fileName(self.currentIndex)
            parentname = self.model.fileName(self.model.parent(self.currentIndex))
            isdir = self.model.isDir(self.currentIndex)
            parentisdir = self.model.isDir(self.model.parent(self.currentIndex))
            # print "%s %s %s %s" % (name, parentname,isdir,parentisdir)
            if isdir and regex.exactMatch(name):
                # We have a database dir
                # print "Database Dir"
                classification = "database"
            elif parentisdir and regex.exactMatch(parentname):
                # We have a dataset
                # print "Dataset Dir"
                classification = "dataset"
        else:
            regex = QRegExp("\\d{4}")
            model = self.model
            parentIndex = model.parent(self.currentIndex)
            parentparentIndex = model.parent(parentIndex)
            parentparentname = model.fileName(parentparentIndex)
            parentparentisdir = model.isDir(parentparentIndex)
            if parentparentisdir and regex.exactMatch(parentparentname):
                # We have a file with a parentparent which is a database classification
                classification = "array"

        # Build up a list of available operations based on the classification

        tool_set_nodes = [tool_set_node for tool_set_node in self.tool_library_node
                          if tool_set_node.tag == 'tool_group']
        tool_file_nodes = []
        for tool_set_node in tool_set_nodes:
            tool_file_nodes.extend([node for node in tool_set_node
                           if node.tag == 'tool'])

        # Find all tool_nodes that acts on the resolved classification
        # (by looking at the XML node 'acts_on')
        for tool_node in tool_file_nodes:
            acts_on_node = tool_node.find('acts_on')
            exports_to_node = tool_node.find('exports_to')

            if acts_on_node is None or exports_to_node is None:
                # This tool doesn't export anything
                continue

            tool_classifications = acts_on_node.text.split(',')
            exports_to_value = exports_to_node.text
            if classification in tool_classifications:
                choices[exports_to_value] = tool_node

        self.classification = classification
        return choices
开发者ID:christianurich,项目名称:VIBe2UrbanSim,代码行数:60,代码来源:file_controller_opus_data.py

示例13: findcontrol

 def findcontrol(self, name):
     regex = QRegExp("^{}$".format(QRegExp.escape(name)))
     regex.setCaseSensitivity(Qt.CaseInsensitive)
     try:
         widget = self.findChildren(QWidget, regex)[0]
     except IndexError:
         widget = None
     return widget
开发者ID:skeenp,项目名称:Roam,代码行数:8,代码来源:featureform.py

示例14: getIndent

    def getIndent(self,text):
		spaces= QRegExp("^(\\s*).*$")
		#~ indentation=""
		#~ if len(text) > 0 and text[-1] in [':', '{', '(', '[']:
				#~ indentation="	"
		if spaces.indexIn(text) == -1:
			return ""
		return spaces.cap(1)
开发者ID:andres53016,项目名称:ejemplo1,代码行数:8,代码来源:codeedit.py

示例15: __init__

 def __init__(self, parent=None):
     super(RomanSpinBox, self).__init__(parent)
     regex = QRegExp(r"^M?M?M?(?:CM|CD|D?C?C?C?)"
                     r"(?:XC|XL|L?X?X?X?)(?:IX|IV|V?I?I?I?)$")
     regex.setCaseSensitivity(Qt.CaseInsensitive)
     self.validator = QRegExpValidator(regex, self)
     self.setRange(1, 3999)
     self.lineEdit().textEdited.connect(self.fixCase)
开发者ID:imagingearth,项目名称:PyQt4-Examples,代码行数:8,代码来源:romanspinbox.py


注:本文中的PyQt4.QtCore.QRegExp类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。