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


C++ QRegularExpression::setPattern方法代码示例

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


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

示例1: handleCurrentArticleChanged

// display a news
void RSSWidget::handleCurrentArticleChanged(const QModelIndex &currentIndex, const QModelIndex &previousIndex)
{
    m_ui->textBrowser->clear();

    if (previousIndex.isValid()) {
        RSS::Article *article = getArticlePtr(previousIndex);
        Q_ASSERT(article);
        article->markAsRead();
    }

    if (!currentIndex.isValid()) return;

    RSS::Article *article = getArticlePtr(currentIndex);
    Q_ASSERT(article);

    QString html;
    html += "<div style='border: 2px solid red; margin-left: 5px; margin-right: 5px; margin-bottom: 5px;'>";
    html += "<div style='background-color: #678db2; font-weight: bold; color: #fff;'>" + article->title() + "</div>";
    if (article->date().isValid())
        html += "<div style='background-color: #efefef;'><b>" + tr("Date: ") + "</b>" + article->date().toLocalTime().toString(Qt::SystemLocaleLongDate) + "</div>";
    if (!article->author().isEmpty())
        html += "<div style='background-color: #efefef;'><b>" + tr("Author: ") + "</b>" + article->author() + "</div>";
    html += "</div>";
    html += "<div style='margin-left: 5px; margin-right: 5px;'>";
    if (Qt::mightBeRichText(article->description())) {
        html += article->description();
    }
    else {
        QString description = article->description();
        QRegularExpression rx;
        // If description is plain text, replace BBCode tags with HTML and wrap everything in <pre></pre> so it looks nice
        rx.setPatternOptions(QRegularExpression::InvertedGreedinessOption
            | QRegularExpression::CaseInsensitiveOption);

        rx.setPattern("\\[img\\](.+)\\[/img\\]");
        description = description.replace(rx, "<img src=\"\\1\">");

        rx.setPattern("\\[url=(\")?(.+)\\1\\]");
        description = description.replace(rx, "<a href=\"\\2\">");
        description = description.replace("[/url]", "</a>", Qt::CaseInsensitive);

        rx.setPattern("\\[(/)?([bius])\\]");
        description = description.replace(rx, "<\\1\\2>");

        rx.setPattern("\\[color=(\")?(.+)\\1\\]");
        description = description.replace(rx, "<span style=\"color:\\2\">");
        description = description.replace("[/color]", "</span>", Qt::CaseInsensitive);

        rx.setPattern("\\[size=(\")?(.+)\\d\\1\\]");
        description = description.replace(rx, "<span style=\"font-size:\\2px\">");
        description = description.replace("[/size]", "</span>", Qt::CaseInsensitive);

        html += "<pre>" + description + "</pre>";
    }
    html += "</div>";
    m_ui->textBrowser->setHtml(html);
}
开发者ID:glassez,项目名称:qBittorrent,代码行数:58,代码来源:rsswidget.cpp

示例2: toInt

int Walltime::toInt( QString const& string )
{
    int h,m;
    int s = -1;
    QRegularExpression re;
    QRegularExpressionMatch rem;
 // "h+:mm:ss"
    re.setPattern("^(\\d+):(\\d+):(\\d+)");
    rem = re.match(string);
    if( rem.hasMatch() ) {
        try {
            h = rem.captured(1).toInt();
            m = rem.captured(2).toInt();
            s = rem.captured(3).toInt();
            s+= h*3600 + m*60;
        } catch(...) {
            s = -1;
        }
        return s;
    }
 // "<integer>unit" where unit is d|h|m|s (case insensitive)
    re.setPattern("^\\s*(\\d+)\\s*([dhmsDHMS]?)\\s*$");
    rem = re.match( string );
    if( rem.hasMatch() ) {
        QString number = rem.captured(1);
        QString unit   = rem.captured(2);
        try {
            s = number.toInt();
            if( s<0 ) s = -1;
            else if( unit=="d" ) s*=24*3600;
            else if( unit=="h" ) s*=3600;
            else if( unit=="m" ) s*=60;
            else if( unit=="s" ) s*=1;
            else s = -1;
        } catch(...) {
            s = -1;
        }
        return s;
    }
 // "h+:mm"
    re.setPattern("^\\s*(\\d+):(\\d+)\\s*$");
    rem = re.match( string );
    if( rem.hasMatch() ) {
        try {
            h = rem.captured(1).toInt();
            m = rem.captured(2).toInt();
            s = h*3600 + m*60;
        } catch(...) {
            s = -1;
        }
        return s;
    }
    return -1; //keep the compiler happy
}
开发者ID:hpcuantwerpen,项目名称:Launcher,代码行数:54,代码来源:walltime.cpp

示例3: setRating

bool Ratings::setRating(const QString& val, RatingAgency ag)
{
    qint32 agencyIndex;

    for (agencyIndex = 0;; ++agencyIndex) {
        Q_ASSERT(agencyIndex <= CountRatingAcencies);
        if (static_cast<qint32>(ag) == (1 << agencyIndex))
            break;
    }
    /////////////////Fix for bloomberg return values in excel//////////////////
    if (val.trimmed().toUpper().left(4) == "#N/A") {
        setRating(RatingValue::NR, ag);
        setWatch(Stable, ag);
        return true;
    }
    //////////////////////////////////////////////////////////////////////////
    const  auto agencySyntax = RatingsPrivate::m_ratingSyntax[agencyIndex];
    QRegularExpression syntaxCheck;
    syntaxCheck.setPatternOptions(QRegularExpression::CaseInsensitiveOption | QRegularExpression::DontCaptureOption);
    for (int i = static_cast<qint16>(RatingValue::AAA); i <= static_cast<qint16>(RatingValue::Dm); ++i){
        if (!agencySyntax[i].isEmpty()) {
            syntaxCheck.setPattern(
                "(^|[^" + QRegularExpression::escape(RatingsPrivate::m_reservedChars[agencyIndex]) + "])"
                + QRegularExpression::escape(agencySyntax[i])
                + "($|[^" + QRegularExpression::escape(RatingsPrivate::m_reservedChars[agencyIndex]) + "])"
                );
            Q_ASSERT(syntaxCheck.isValid());
            if (syntaxCheck.match(val).hasMatch()){
                    setRating(static_cast<RatingValue>(i), ag);
                    break;
            }
        }
        if (i == static_cast<qint16>(RatingValue::Dm)) {
            setRating(RatingValue::NR, ag, Stable);
            return false;
        }
    }
    if (val.indexOf("*-", 0, Qt::CaseInsensitive) >= 0)
        setWatch(Negative, ag);
    else if (val.indexOf("*+", 0, Qt::CaseInsensitive) >= 0)
        setWatch(Positive, ag);
    else
        setWatch(Stable, ag);
    return true;
}
开发者ID:bubble501,项目名称:CLOModel,代码行数:45,代码来源:Ratings.cpp

示例4: main

int main() {

{
//! [0]
QRegularExpression re("a pattern");
//! [0]
}

{
//! [1]
QRegularExpression re;
re.setPattern("another pattern");
//! [1]
}

{
//! [2]
// matches two digits followed by a space and a word
QRegularExpression re("\\d\\d \\w+");

// matches a backslash
QRegularExpression re2("\\\\");
//! [2]
}

{
//! [3]
QRegularExpression re("a third pattern");
QString pattern = re.pattern(); // pattern == "a third pattern"
//! [3]
}

{
//! [4]
// matches "Qt rocks", but also "QT rocks", "QT ROCKS", "qT rOcKs", etc.
QRegularExpression re("Qt rocks", QRegularExpression::CaseInsensitiveOption);
//! [4]
}

{
//! [5]
QRegularExpression re("^\\d+$");
re.setPatternOptions(QRegularExpression::MultilineOption);
// re matches any line in the subject string that contains only digits (but at least one)
//! [5]
}

{
//! [6]
QRegularExpression re = QRegularExpression("^two.*words$", QRegularExpression::MultilineOption
                                                           | QRegularExpression::DotMatchesEverythingOption);

QRegularExpression::PatternOptions options = re.patternOptions();
// options == QRegularExpression::MultilineOption | QRegularExpression::DotMatchesEverythingOption
//! [6]
}

{
//! [7]
// match two digits followed by a space and a word
QRegularExpression re("\\d\\d \\w+");
QRegularExpressionMatch match = re.match("abc123 def");
bool hasMatch = match.hasMatch(); // true
//! [7]
}

{
//! [8]
QRegularExpression re("\\d\\d \\w+");
QRegularExpressionMatch match = re.match("abc123 def");
if (match.hasMatch()) {
    QString matched = match.captured(0); // matched == "23 def"
    // ...
}
//! [8]
}

{
//! [9]
QRegularExpression re("\\d\\d \\w+");
QRegularExpressionMatch match = re.match("12 abc 45 def", 1);
if (match.hasMatch()) {
    QString matched = match.captured(0); // matched == "45 def"
    // ...
}
//! [9]
}

{
//! [10]
QRegularExpression re("^(\\d\\d)/(\\d\\d)/(\\d\\d\\d\\d)$");
QRegularExpressionMatch match = re.match("08/12/1985");
if (match.hasMatch()) {
    QString day = match.captured(1); // day == "08"
    QString month = match.captured(2); // month == "12"
    QString year = match.captured(3); // year == "1985"
    // ...
}
//! [10]
}
//.........这里部分代码省略.........
开发者ID:SchleunigerAG,项目名称:WinEC7_Qt5.3.1_Fixes,代码行数:101,代码来源:src_corelib_tools_qregularexpression.cpp

示例5: data

void Reader_RFM008B::readData()
{
    if(m_serial->canReadLine()){
        if(!allLines){

//            Logger::instance()->writeRecord(Logger::severity_level::debug, m_module, Q_FUNC_INFO, QString("Reading Data..."));

            QByteArray buffer = m_serial->readAll();
            QRegExp regex;
            regex.setPattern("(L(\\d{2})?W)\\s([0-9a-fA-F]{4})\\s([0-9a-fA-F]{16})");

            QString data(buffer);
            data.remove(QRegExp("[\\n\\t\\r]"));

            //        if(m_outReceived.device()){
            //            m_outReceived << data;
            //            m_outReceived.flush();
            //        }


            int pos = regex.indexIn(data);
            if(pos != -1){
                // The first string in the list is the entire matched string.
                // Each subsequent list element contains a string that matched a
                // (capturing) subexpression of the regexp.
                QStringList matches = regex.capturedTexts();

                // crear RFIDData
                QRegularExpression regexCode;
                regexCode.setPattern("([0-9a-fA-F]{4})(\\s)([0-9a-fA-F]{16})");
                QRegularExpressionMatch match = regexCode.match(matches.at(0));

                if(m_outCaptured.device()){
                    m_outCaptured << matches.at(0);
                    m_outCaptured.flush();
                }

                if(match.hasMatch()) {
                    Rfiddata *data = new Rfiddata(this);

                    // Id collector from configuration file
                    data->setIdpontocoleta(idCollector);

                    // This module can read from only one antena, so the idAntena is static.
                    int idAntena = 1;
                    data->setIdantena(idAntena);

                    qlonglong applicationcode = match.captured(1).toLongLong();
                    qlonglong identificationcode = match.captured(3).toLongLong();

                    /*
                 * Filter by time. If more than one transponder was read in a time interval only one of them will be persisted.
                 * A QMap is used to verify if each new data that had arrived was already read in this interval.
                 */
                    if(!m_map.contains(identificationcode)){

                        QTimer *timer = new QTimer;
                        timer->setSingleShot(true);
                        timer->setInterval(1000);
                        connect(timer, &QTimer::timeout,
                                [=, this]()
                        {
                            this->m_map.remove(identificationcode);
                            timer->deleteLater();
                        });
                        m_map.insert(identificationcode, timer);
                        timer->start();

                        data->setApplicationcode(applicationcode);
                        data->setIdentificationcode(identificationcode);
                        data->setDatetime(QDateTime::currentDateTime());
                        data->setSync(Rfiddata::KNotSynced);

                        QList<Rfiddata*> list;
                        list.append(data);
                        try {
                            PersistenceInterface *persister = qobject_cast<PersistenceInterface *>(RFIDMonitor::instance()->defaultService(ServiceType::KPersister));
                            Q_ASSERT(persister);
                            SynchronizationInterface *synchronizer = qobject_cast<SynchronizationInterface*>(RFIDMonitor::instance()->defaultService(ServiceType::KSynchronizer));
                            Q_ASSERT(synchronizer);

#ifdef CPP_11_ASYNC
                            /*C++11 std::async Version*/
                            std::function<void(const QList<Rfiddata *>&)> persistence = std::bind(&PersistenceInterface::insertObjectList, persister, std::placeholders::_1);
                            std::async(std::launch::async, persistence, list);
                            std::function<void()> synchronize = std::bind(&SynchronizationInterface::readyRead, synchronizer);
                            std::async(std::launch::async, synchronize);
#else
                            /*Qt Concurrent Version*/
                            QtConcurrent::run(persister, &PersistenceInterface::insertObjectList, list);
                            QtConcurrent::run(synchronizer, &SynchronizationInterface::readyRead);
#endif
                        } catch (std::exception &e) {
                            Logger::instance()->writeRecord(Logger::severity_level::fatal, m_module, Q_FUNC_INFO, e.what());
                        }
                    }
                }
            }
        }else{

//.........这里部分代码省略.........
开发者ID:CELTAB,项目名称:rfidmonitor,代码行数:101,代码来源:reader_rfm008b.cpp

示例6: parseAgent

DATA::Agent LiliHelper::parseAgent(const QString aPath, const QStringList aAliases, const QString aSheet)
{
    QXlsx::Document aDocument (aPath);
    DATA::Agent aAgent;

    QStringList aStringList;
    if (aSheet.length() != 0)
    {
        aStringList.append(aSheet);
    }
    else
    {
        aStringList = aDocument.sheetNames();
    }

    for (auto aSheet : aStringList)
    {
        aDocument.selectSheet(aSheet);
        QXlsx::CellRange aSheetRange (aDocument.dimension());

        QHash<QString, QDate> aRefDateMap;
        QDate aCurrentDate;
        QString aNote;
        for (int nRow = aSheetRange.firstRow(); nRow <= aSheetRange.lastRow(); ++nRow)
        {
            QVariant aCell = aDocument.read(nRow, 2);
            const bool bFirst = aCell.type() == QVariant::String && s_aWeekDays.contains(aCell.toString());

            if (bFirst)
            {
                if (aDocument.read(nRow, 19).type() == QVariant::String)
                {
                    aNote = aDocument.read(nRow, 19).toString();
                }

                QString aCellRef = QXlsx::CellReference (nRow, 9).toString();
                QVariant aDateVariant = aDocument.read(aCellRef);

                // Looking for date without reference
                if (!aCurrentDate.isValid() && aDateVariant.type() == QVariant::Date)
                {
                    aCurrentDate = aDateVariant.toDate();
                    aRefDateMap.insert(aCellRef, aCurrentDate);
                }

                // Looking for date with reference
                else if (aCurrentDate.isValid() && aDateVariant.type() == QVariant::String)
                {
                    QRegularExpression aRx;
                    QRegularExpressionMatchIterator aRxIterator;
                    aRx.setPattern("=(\\w+\\d+)\\+(\\d+)");

                    aRxIterator = aRx.globalMatch(aDateVariant.toString());

                    if (aRxIterator.hasNext())
                    {
                        QRegularExpressionMatch aMatch = aRxIterator.next();
                        QString aReferencedCell = aMatch.captured(1);
                        if (aRefDateMap.contains(aReferencedCell))
                        {
                            aCurrentDate = aRefDateMap[aReferencedCell].addDays(aMatch.captured(2).toInt());
                            aRefDateMap.insert(aCellRef, aCurrentDate);
                        }
                    }
                }

            }
            else if (aCurrentDate.isValid())
            {
                QVariant aNameVariant = aDocument.read(nRow, 1);
                if (aNameVariant.type() == QVariant::String && aAliases.contains(aNameVariant.toString()))
                {
                    int nHourHead = 2;
                    while (nHourHead <= 54)
                    {
                        QVariant aVariant = aDocument.read(nRow, nHourHead);
                        int nTempHead = nHourHead + 1;

                        if (aVariant.type() == QVariant::Double && aVariant.toInt() == 1)
                        {
                            QTime aStartTime (7, 0);
                            if (nHourHead > 2)
                            {
                                aStartTime = aStartTime.addSecs(1800 + (nHourHead - 3) * 900);
                            }
                            QTime aEndTime = aStartTime.addSecs(15 * 60);
                            aVariant = aDocument.read(nRow, nTempHead);
                            while (nTempHead <= 54 && aVariant.type() == QVariant::Double && aVariant.toInt() == 1)
                            {
                                aEndTime = aEndTime.addSecs(15 * 60);
                                ++nTempHead;
                                aVariant = aDocument.read(nRow, nTempHead);
                            }
                            aAgent.getEvents().append(DATA::CalEvent (QDateTime (aCurrentDate, aStartTime),
                                                                      QDateTime (aCurrentDate, aEndTime),
                                                                      aNote));
                        }

                        nHourHead = nTempHead;
                    }
//.........这里部分代码省略.........
开发者ID:Neirbo888,项目名称:lilicalendar,代码行数:101,代码来源:LiliHelper.cpp

示例7: generateICSDataHash

/**
 * @brief Parses and transforms the ics data to a hash with the data
 * @param icsData
 * @return
 */
void CalendarItem::generateICSDataHash() {
    QRegularExpression regex;
    QRegularExpressionMatch match;
    QString lastKey;
    icsDataKeyList.clear();
    icsDataHash.clear();

    QStringList iscDataLines = icsData.split("\n");

    QListIterator<QString> i(iscDataLines);
    while (i.hasNext()) {
        QString line = i.next();
        line.replace("\r", "");

        if (line == "") {
            continue;
        }

        // multi-line text stats with a space
        if (!line.startsWith(" ")) {
            // remove the trailing \n
            if (line.endsWith("\n")) {
                line.chop(1);
            }

            // parse key and value
            regex.setPattern("^([A-Z\\-_=;]+):(.*)$");
            match = regex.match(line);

            // set last key for multi line texts
            lastKey = match.captured(1);

            if (lastKey == "") {
                continue;
            }

            // find a free key
            lastKey = findFreeHashKey(&icsDataHash, lastKey);

            // add new key / value pair to the hash
            icsDataHash[lastKey] = decodeICSDataLine(match.captured(2));
//            hash.insert( lastKey, decodeICSDataLine( match.captured(2) ) );

            // add the key to the key order list
            icsDataKeyList.append(lastKey);
        }
        else {
            // remove the trailing \n
            if (line.endsWith("\n")) {
                line.chop(1);
            }

            // remove leading space
            regex.setPattern("^ (.+)$");
            match = regex.match(line);

            // add text to last line
            icsDataHash[lastKey] += decodeICSDataLine(match.captured(1));
        }
    }
}
开发者ID:Fabijenna,项目名称:QOwnNotes,代码行数:66,代码来源:calendaritem.cpp

示例8: url

Load::Load(QObject *parent) : QObject(parent), d_ptr(new LoadPrivate(this))
{
	Q_D(Load);
	ins = this;
	setObjectName("Load");

	auto avProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString i = task.code.mid(2, sharp - 2);
			QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1);
			QString url("http://www.%1/video/av%2/");
			url = url.arg(Utils::customUrl(Utils::Bilibili)).arg(i);
			if (!p.isEmpty()){
				url += QString("index_%1.html").arg(p);
			}
			forward(QNetworkRequest(url), Page);
			break;
		}
		case Page:
		{
			d->model->clear();
			QString api, id, video(reply->readAll());
			int part = video.indexOf("<select");
			if (part != -1 && sharp == -1){
				QRegularExpression r("(?<=>).*?(?=</option>)");
				QStringRef list(&video, part, video.indexOf("</select>", part) - part);
				QRegularExpressionMatchIterator i = r.globalMatch(list);
				api = "http://www.%1/video/%2/index_%3.html";
				api = api.arg(Utils::customUrl(Utils::Bilibili));
				while (i.hasNext()){
					int index = d->model->rowCount() + 1;
					QStandardItem *item = new QStandardItem;
					item->setData(QUrl(api.arg(task.code).arg(index)), UrlRole);
					item->setData((task.code + "#%1").arg(index), StrRole);
					item->setData(Page, NxtRole);
					item->setData(Utils::decodeXml(i.next().captured()), Qt::EditRole);
					d->model->appendRow(item);
				}
			}
			if (d->model->rowCount() > 0){
				emit stateChanged(task.state = Part);
			}
			else{
				QRegularExpression r = QRegularExpression("cid[=\":]*\\d+", QRegularExpression::CaseInsensitiveOption);
				QRegularExpressionMatchIterator i = r.globalMatch(video);
				while (i.hasNext()){
					QString m = i.next().captured();
					m = QRegularExpression("\\d+").match(m).captured();
					if (id.isEmpty()){
						id = m;
					}
					else if (id != m){
						id.clear();
						break;
					}
				}
				if (!id.isEmpty()){
					api = "http://comment.%1/%2.xml";
					api = api.arg(Utils::customUrl(Utils::Bilibili));
					forward(QNetworkRequest(api.arg(id)), File);
				}
                else{
                    emit stateChanged(203);
                    qDebug() << "Fail to load danmaku, try biliApi";
                    dequeue();
                }
            }
			break;
		}
		case File:
		{
			dumpDanmaku(reply->readAll(), Utils::Bilibili, false);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	auto avRegular = [](QString &code){
		code.remove(QRegularExpression("/index(?=_\\d+\\.html)"));
		QRegularExpression r("a(v(\\d+([#_])?(\\d+)?)?)?");
		r.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
		return getRegular(r)(code);
	};
	d->pool.append({ avRegular, 0, avProcess });

	auto bbProcess = [this, avProcess](QNetworkReply *reply) {
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state) {
		case None:
		{
			QString i = task.code.mid(2);
			QString u = "http://www.%1/bangumi/i/%2/";
			u = u.arg(Utils::customUrl(Utils::Bilibili)).arg(i);
//.........这里部分代码省略.........
开发者ID:FantasyNJ,项目名称:BiliLocal-OSX,代码行数:101,代码来源:Load.cpp


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