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


C++ QRegularExpression类代码示例

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


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

示例1: reURLScheme

bool Utils::Misc::isUrl(const QString &s)
{
    static const QRegularExpression reURLScheme(
                "http[s]?|ftp", QRegularExpression::CaseInsensitiveOption);

    return reURLScheme.match(QUrl(s).scheme()).hasMatch();
}
开发者ID:ATGardner,项目名称:qBittorrent,代码行数:7,代码来源:misc.cpp

示例2: createRegExp

QList<LocatorFilterEntry> OpenDocumentsFilter::matchesFor(QFutureInterface<LocatorFilterEntry> &future,
                                                          const QString &entry)
{
    QList<LocatorFilterEntry> goodEntries;
    QList<LocatorFilterEntry> betterEntries;
    const EditorManager::FilePathInfo fp = EditorManager::splitLineAndColumnNumber(entry);

    const QRegularExpression regexp = createRegExp(fp.filePath);
    if (!regexp.isValid())
        return goodEntries;

    const QList<Entry> editorEntries = editors();
    for (const Entry &editorEntry : editorEntries) {
        if (future.isCanceled())
            break;
        QString fileName = editorEntry.fileName.toString();
        if (fileName.isEmpty())
            continue;
        QString displayName = editorEntry.displayName;
        const QRegularExpressionMatch match = regexp.match(displayName);
        if (match.hasMatch()) {
            LocatorFilterEntry filterEntry(this, displayName, QString(fileName + fp.postfix));
            filterEntry.extraInfo = FileUtils::shortNativePath(FileName::fromString(fileName));
            filterEntry.fileName = fileName;
            filterEntry.highlightInfo = highlightInfo(match);
            if (match.capturedStart() == 0)
                betterEntries.append(filterEntry);
            else
                goodEntries.append(filterEntry);
        }
    }
    betterEntries.append(goodEntries);
    return betterEntries;
}
开发者ID:choenig,项目名称:qt-creator,代码行数:34,代码来源:opendocumentsfilter.cpp

示例3: parseImageFormat

  ImageOutputFormat parseImageFormat( const QString &format )
  {
    if ( format.compare( QLatin1String( "png" ), Qt::CaseInsensitive ) == 0 ||
         format.compare( QLatin1String( "image/png" ), Qt::CaseInsensitive ) == 0 )
    {
      return PNG;
    }
    else if ( format.compare( QLatin1String( "jpg " ), Qt::CaseInsensitive ) == 0  ||
              format.compare( QLatin1String( "image/jpeg" ), Qt::CaseInsensitive ) == 0 )
    {
      return JPEG;
    }
    else
    {
      // lookup for png with mode
      QRegularExpression modeExpr = QRegularExpression( QStringLiteral( "image/png\\s*;\\s*mode=([^;]+)" ),
                                    QRegularExpression::CaseInsensitiveOption );

      QRegularExpressionMatch match = modeExpr.match( format );
      QString mode = match.captured();
      if ( mode.compare( QLatin1String( "16bit" ), Qt::CaseInsensitive ) == 0 )
        return PNG16;
      if ( mode.compare( QLatin1String( "8bit" ), Qt::CaseInsensitive ) == 0 )
        return PNG8;
      if ( mode.compare( QLatin1String( "1bit" ), Qt::CaseInsensitive ) == 0 )
        return PNG1;
    }

    return UNKN;
  }
开发者ID:exlimit,项目名称:QGIS,代码行数:30,代码来源:qgswmsutils.cpp

示例4: fontRegistry

static FontKeys &fontKeys()
{
    static FontKeys result;
    if (result.isEmpty()) {
        const QSettings fontRegistry(QStringLiteral("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"),
                                     QSettings::NativeFormat);
        const QStringList allKeys = fontRegistry.allKeys();
        const QString trueType = QStringLiteral("(TrueType)");
        const QRegularExpression sizeListMatch(QStringLiteral("\\s(\\d+,)+\\d+"));
        Q_ASSERT(sizeListMatch.isValid());
        const int size = allKeys.size();
        result.reserve(size);
        for (int i = 0; i < size; ++i) {
            FontKey fontKey;
            const QString &registryFontKey = allKeys.at(i);
            fontKey.fileName = fontRegistry.value(registryFontKey).toString();
            QString realKey = registryFontKey;
            realKey.remove(trueType);
            realKey.remove(sizeListMatch);
            const QStringList fontNames = realKey.trimmed().split(QLatin1Char('&'));
            fontKey.fontNames.reserve(fontNames.size());
            foreach (const QString &fontName, fontNames)
                fontKey.fontNames.append(fontName.trimmed());
            result.append(fontKey);
        }
    }
    return result;
}
开发者ID:MarianMMX,项目名称:MarianMMX,代码行数:28,代码来源:qwindowsfontdatabase_ft.cpp

示例5: createProposal

static void createProposal(QFutureInterface<QStringList> &future, const QString &text,
                           const QString &wordUnderCursor)
{
    const QRegularExpression wordRE("([a-zA-Z_][a-zA-Z0-9_]{2,})");

    QSet<QString> words;
    QRegularExpressionMatchIterator it = wordRE.globalMatch(text);
    int wordUnderCursorFound = 0;
    while (it.hasNext()) {
        if (future.isCanceled())
            return;
        QRegularExpressionMatch match = it.next();
        const QString &word = match.captured();
        if (word == wordUnderCursor) {
            // Only add the word under cursor if it
            // already appears elsewhere in the text
            if (++wordUnderCursorFound < 2)
                continue;
        }

        if (!words.contains(word))
            words.insert(word);
    }

    future.reportResult(words.toList());
}
开发者ID:kai66673,项目名称:qt-creator,代码行数:26,代码来源:documentcontentcompletion.cpp

示例6: Q_ASSERT

bool CRegularExpressionRule::match(const QList<QString>& lQuery, const QString& sContent) const
{
	Q_ASSERT( m_nType == RuleType::RegularExpression );

	if ( m_sContent.isEmpty() )
		return false;

	if ( m_bSpecialElements )
	{
		// Build a regular expression filter from the search query words.
		// Returns an empty string if not applied or if the filter was invalid.
		//
		// Substitutes:
		// <_> - inserts all query keywords;
		// <0>..<9> - inserts query keyword number 0..9;
		// <> - inserts next query keyword.
		//
		// For example regular expression:
		//	.*(<2><1>)|(<_>).*
		// for "music mp3" query will be converted to:
		//	.*(mp3\s*music\s*)|(music\s*mp3\s*).*
		//
		// Note: \s* - matches any number of white-space symbols (including zero).

		QString sFilter, sBaseFilter = m_sContent;

		int pos = sBaseFilter.indexOf( '<' );
		if ( pos != -1 )
		{
			quint8 nArg = 0;

			// replace all relevant occurrences of <*something*
			while ( pos != -1 );
			{
				sFilter += sBaseFilter.left( pos );
				sBaseFilter.remove( 0, pos );
				bool bSuccess = replace( sBaseFilter, lQuery, nArg );

				pos = sBaseFilter.indexOf( '<', bSuccess ? 0 : 1 );
			}
			// add whats left of the base filter string to the newly generated filter
			sFilter += sBaseFilter;

			QRegularExpression oRegExpFilter = QRegularExpression( sFilter );
			return oRegExpFilter.match( sContent ).hasMatch();
		}
		else
		{
			// This shouldn't happen, but it's covered anyway...
			Q_ASSERT( false );

			QRegularExpression oRegExpFilter = QRegularExpression( m_sContent );
			return oRegExpFilter.match( sContent ).hasMatch();
		}
	}
	else
	{
		return m_regularExpressionContent.match( sContent ).hasMatch();
	}
}
开发者ID:quazaa-development-team,项目名称:quazaa,代码行数:60,代码来源:regexprule.cpp

示例7: QDir

// Delete all temporary directories for an application
int PathUtils::removeTemporaryApplicationDirs(QString appName) {
    if (appName.isNull()) {
        appName = qApp->applicationName();
    }

    auto dirName = TEMP_DIR_FORMAT.arg(appName).arg("*").arg("*");

    QDir rootTempDir = QDir::tempPath();
    auto dirs = rootTempDir.entryInfoList({ dirName }, QDir::Dirs);
    int removed = 0;
    for (auto& dir : dirs) {
        auto dirName = dir.fileName();
        auto absoluteDirPath = QDir(dir.absoluteFilePath());
        QRegularExpression re { "^" + QRegularExpression::escape(appName) + "\\-(?<pid>\\d+)\\-(?<timestamp>\\d+)$" };

        auto match = re.match(dirName);
        if (match.hasMatch()) {
            auto pid = match.capturedRef("pid").toLongLong();
            auto timestamp = match.capturedRef("timestamp");
            if (!processIsRunning(pid)) {
                qDebug() << "  Removing old temporary directory: " << dir.absoluteFilePath();
                absoluteDirPath.removeRecursively();
                removed++;
            } else {
                qDebug() << "  Not removing (process is running): " << dir.absoluteFilePath();
            }
        }
    }

    return removed;
}
开发者ID:AndrewMeadows,项目名称:hifi,代码行数:32,代码来源:PathUtils.cpp

示例8: readIdentifierOrKeyword

NimLexer::Token NimLexer::readIdentifierOrKeyword(SourceCodeStream* stream)
{
    static QRegularExpression isLetter {"[a-zA-Z\x80-\xFF]"};
    static QSet<QString> keywords {"template", "include", // 7
                                   "method", "string", "import" // 6
                                   "while", "cbool", "tuple", "defer", // 5
                                   "cint", "case", "bool", "proc", "type",
                                   "else", "from", "enum", "when", // 4
                                   "int", "var", "for", "ref", // 3
                                   "in", "of", "if" }; // 2
    stream->setAnchor();
    stream->move();

    while (!stream->isEnd()) {
        const QChar& c = stream->peek();
        if (!(c == '_' || c.isDigit() || isLetter.match(c).hasMatch()))
            break;
        stream->move();
    }

    QString value = stream->value();
    bool isKeyword = keywords.contains(value);

    return Token (stream->anchor(),
                  stream->length(),
                  isKeyword ? TokenType::Keyword : TokenType::Identifier );
}
开发者ID:filcuc,项目名称:NimSyntaxHighlighter,代码行数:27,代码来源:nimlexer.cpp

示例9: Q_D

QByteArray ViewJson::render(Context *c) const
{
    Q_D(const ViewJson);

    QByteArray ret;
    QJsonObject obj;

    const QVariantHash stash = c->stash();

    switch (d->exposeMode) {
    case All:
        obj = QJsonObject::fromVariantHash(stash);
        break;
    case String:
    {
        auto it = stash.constFind(d->exposeKey);
        if (it != stash.constEnd()) {
            obj.insert(d->exposeKey, QJsonValue::fromVariant(it.value()));
        }
        break;
    }
    case StringList:
    {
        QVariantHash exposedStash;

        auto it = stash.constBegin();
        while (it != stash.constEnd()) {
            const QString key = it.key();
            if (d->exposeKeys.contains(key)) {
                exposedStash.insertMulti(it.key(), it.value());
            }
            ++it;
        }
        obj = QJsonObject::fromVariantHash(exposedStash);
        break;
    }
    case RegularExpression:
    {
        QVariantHash exposedStash;
        QRegularExpression re = d->exposeRE; // thread safety

        auto it = stash.constBegin();
        while (it != stash.constEnd()) {
            const QString key = it.key();
            if (re.match(key).hasMatch()) {
                exposedStash.insertMulti(key, it.value());
            }
            ++it;
        }
        obj = QJsonObject::fromVariantHash(exposedStash);
        break;
    }
    }

    c->response()->setContentType(QStringLiteral("application/json"));

    ret = QJsonDocument(obj).toJson(d->format);
    return ret;
}
开发者ID:buschmann23,项目名称:cutelyst,代码行数:59,代码来源:viewjson.cpp

示例10: isWildCard

QRegularExpression SearchOptions::getRegularExpression() const
{
  QRegularExpression regexp = isWildCard() ? StringUtil::wildCardToRegExp(getFindValue()) : QRegularExpression(getFindValue());
  if (!isCaseSensitive()) {
    regexp.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
  }
  return regexp;
}
开发者ID:pitonyak,项目名称:ADPStampInventory,代码行数:8,代码来源:searchoptions.cpp

示例11: az

/** Redefined to disable search in the table and trigger jumpToWidget's action. */
void TableView::keyboardSearch(const QString &search)
{
	// If one has assigned a simple key like 'N' to 'Skip Forward' we don't actually want to skip the track
	// IMHO, it's better to trigger the JumpTo widget to 'N' section
	static QRegularExpression az("[a-z]", QRegularExpression::CaseInsensitiveOption | QRegularExpression::OptimizeOnFirstUsageOption);
	if (az.match(search).hasMatch()) {
		this->jumpTo(search);
	}
}
开发者ID:sun-friderick,项目名称:Miam-Player,代码行数:10,代码来源:tableview.cpp

示例12: anchorRE

void RevDesc::on_anchorClicked(const QUrl& link) {
    static QRegularExpression anchorRE("^#(.+)$");
    qDebug() << "clicked on " << link.toDisplayString() << "\n";
    QWebFrame* frame = this->page()->mainFrame();

    QRegularExpressionMatch anchorMatch = anchorRE.match(link.toDisplayString());
    if(anchorMatch.hasMatch()) {
        frame->scrollToAnchor(anchorMatch.captured(1));
    }
}
开发者ID:simonwagner,项目名称:qgitx,代码行数:10,代码来源:revdesc.cpp

示例13: applyPermissionsFromName

static void applyPermissionsFromName(FileInfo &info) {
    static QRegularExpression rx("_PERM_([^_]*)_[^/]*$");
    auto m = rx.match(info.name);
    if (m.hasMatch()) {
        info.permissions = RemotePermissions::fromServerString(m.captured(1));
    }

    for (FileInfo &sub : info.children)
        applyPermissionsFromName(sub);
}
开发者ID:owncloud,项目名称:client,代码行数:10,代码来源:testpermissions.cpp

示例14: getEncryptedNoteTextRegularExpression

/**
 * Returns encrypted note text if it is encrypted
 */
QString Note::getEncryptedNoteText() {
    QString noteText = this->noteText;

    // get regular expression for the encrypted string
    QRegularExpression re = getEncryptedNoteTextRegularExpression();

    // check if we have an encrypted note text and return it if so
    QRegularExpressionMatch match = re.match(noteText);
    return match.hasMatch() ? match.captured(1) : "";
}
开发者ID:guija,项目名称:QOwnNotes,代码行数:13,代码来源:note.cpp

示例15: Q_ASSERT

void LoginHandler::handleHostMessage(const QString &message)
{
	Q_ASSERT(!_client->username().isEmpty());

	if(_server->sessionCount() >= _server->sessionLimit()) {
		send("ERROR CLOSED");
		_client->disconnectError("login error");
		return;
	}

	const QRegularExpression re("\\AHOST (\\*|[a-zA-Z0-9:-]{1,64}) (\\d+) (\\d+)\\s*(?:;(.+))?\\z");
	auto m = re.match(message);
	if(!m.hasMatch()) {
		send("ERROR SYNTAX");
		_client->disconnectError("login error");
		return;
	}

	QString sessionId = m.captured(1);
	int minorVersion = m.captured(2).toInt();
	int userId = m.captured(3).toInt();

	// Check if session ID is available
	if(sessionId == "*") {
		// Generated session ID
		sessionId = QUuid::createUuid().toString();
		sessionId = sessionId.mid(1, sessionId.length()-2); // strip the { and } chars
	}

	if(!_server->getSessionDescriptionById(sessionId).id.isEmpty()) {
		send("ERROR SESSIONIDINUSE");
		_client->disconnectError("login error");
		return;
	}

	QString password = m.captured(4);
	if(password != _server->hostPassword() && !_hostPrivilege) {
		send("ERROR BADPASS");
		_client->disconnectError("login error");
		return;
	}

	_client->setId(userId);

	// Mark login phase as complete. No more login messages will be sent to this user
	send(QString("OK %1 %2").arg(sessionId).arg(userId));
	_complete = true;

	// Create a new session
	SessionState *session = _server->createSession(sessionId, minorVersion, _client->username());

	session->joinUser(_client, true);

	deleteLater();
}
开发者ID:GreenReaper,项目名称:Drawpile,代码行数:55,代码来源:loginhandler.cpp


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