void GnuMakeParser::stdError(const QString &line) { const QString lne = rightTrimmed(line); QRegularExpressionMatch match = m_errorInMakefile.match(lne); if (match.hasMatch()) { Result res = parseDescription(match.captured(5)); if (res.isFatal) ++m_fatalErrorCount; if (!m_suppressIssues) { taskAdded(Task(res.type, res.description, Utils::FileName::fromUserInput(match.captured(1)) /* filename */, match.captured(4).toInt(), /* line */ Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)), 1, 0); } return; } match = m_makeLine.match(lne); if (match.hasMatch()) { Result res = parseDescription(match.captured(6)); if (res.isFatal) ++m_fatalErrorCount; if (!m_suppressIssues) { Task task = Task(res.type, res.description, Utils::FileName() /* filename */, -1, /* line */ Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)); taskAdded(task, 1, 0); } return; } IOutputParser::stdError(line); }
qint64 reiserfs::readUsedCapacity(const QString& deviceNode) const { ExternalCommand cmd(QStringLiteral("debugreiserfs"), { deviceNode }); if (cmd.run(-1) && cmd.exitCode() == 16) { qint64 blockCount = -1; QRegularExpression re(QStringLiteral("Count of blocks[^:]+: (\\d+)")); QRegularExpressionMatch reBlockCount = re.match(cmd.output()); if (reBlockCount.hasMatch()) blockCount = reBlockCount.captured(1).toLongLong(); qint64 blockSize = -1; re.setPattern(QStringLiteral("Blocksize: (\\d+)")); QRegularExpressionMatch reBlockSize = re.match(cmd.output()); if (reBlockSize.hasMatch()) blockSize = reBlockSize.captured(1).toLongLong(); qint64 freeBlocks = -1; re.setPattern(QStringLiteral("Free blocks[^:]+: (\\d+)")); QRegularExpressionMatch reFreeBlocks = re.match(cmd.output()); if (reFreeBlocks.hasMatch()) freeBlocks = reFreeBlocks.captured(1).toLongLong(); if (blockCount > -1 && blockSize > -1 && freeBlocks > -1) return (blockCount - freeBlocks) * blockSize; } return -1; }
/** * @brief Returns a map of parsed markdown urls with their link texts as key * * @param text * @return parsed urls */ QMap<QString, QString> QMarkdownTextEdit::parseMarkdownUrlsFromText( QString text ) { QMap<QString, QString> urlMap; // match urls like this: [this url](http://mylink) QRegularExpression re("(\\[.*?\\]\\((.+?://.+?)\\))"); QRegularExpressionMatchIterator i = re.globalMatch( text ); while ( i.hasNext() ) { QRegularExpressionMatch match = i.next(); QString linkText = match.captured(1); QString url = match.captured(2); urlMap[linkText] = url; } // match urls like this: <http://mylink> re = QRegularExpression("(<(.+?://.+?)>)"); i = re.globalMatch( text ); while ( i.hasNext() ) { QRegularExpressionMatch match = i.next(); QString linkText = match.captured(1); QString url = match.captured(2); urlMap[linkText] = url; } return urlMap; }
void Application::updateGotCurrent() { if (!updateReply || updateThread) return; cSetLastUpdateCheck(unixtime()); QRegularExpressionMatch m = QRegularExpression(qsl("^\\s*(\\d+)\\s*:\\s*([\\x21-\\x7f]+)\\s*$")).match(QString::fromUtf8(updateReply->readAll())); if (m.hasMatch()) { int32 currentVersion = m.captured(1).toInt(); if (currentVersion > AppVersion) { updateThread = new QThread(); connect(updateThread, SIGNAL(finished()), updateThread, SLOT(deleteLater())); updateDownloader = new PsUpdateDownloader(updateThread, m.captured(2)); updateThread->start(); } } if (updateReply) updateReply->deleteLater(); updateReply = 0; if (!updateThread) { QDir updates(cWorkingDir() + "tupdates"); if (updates.exists()) { QFileInfoList list = updates.entryInfoList(QDir::Files); for (QFileInfoList::iterator i = list.begin(), e = list.end(); i != e; ++i) { if (QRegularExpression("^(tupdate|tmacupd|tlinuxupd|tlinux32upd)\\d+$", QRegularExpression::CaseInsensitiveOption).match(i->fileName()).hasMatch()) { QFile(i->absoluteFilePath()).remove(); } } } emit updateLatest(); } startUpdateCheck(true); App::writeConfig(); }
SteamConfig::Element::Element(QList<QString> *lines) { QString line; QRegularExpression re("\"([^\"]*)\""); QRegularExpressionMatchIterator i; while (lines->length() > 0) { line = lines->front(); lines->pop_front(); i = re.globalMatch(line); if (i.hasNext()) break; } if (!lines->length()) // corrupt return; QRegularExpressionMatch match = i.next(); name = match.captured(1).toLower(); if (i.hasNext()) { // value is a string match = i.next(); value = match.captured(1); value.replace("\\\\", "\\"); } line = lines->front(); if (line.contains("{")) { lines->pop_front(); while (true) { line = lines->front(); if (line.contains("}")) { // empty lines->pop_front(); return; } Element e(lines); children[e.name] = e; } } }
// Handle the general case QString GumboInterface::fix_self_closing_tags(const QString &source) { QString newsource = source; QRegularExpression selfclosed("<\\s*([a-zA-Z]+)(\\s*[^>/]*)/\\s*>"); QRegularExpressionMatch match = selfclosed.match(newsource, 0); while (match.hasMatch()) { if (match.capturedStart() == -1) { break; } QString tag = match.captured(0); int sp = match.capturedStart(0); int n = match.capturedLength(0); QString name = match.captured(1); QString atts = match.captured(2);; atts = atts.trimmed(); if (!atts.isEmpty()) { atts = " " + atts; } int nsp = sp + n; if (!allowed_void_tags.contains(name)) { QString newtag = "<" + name + atts + "></" + name + ">"; newsource = newsource.replace(sp,n,newtag); nsp = sp + newtag.length(); } match = selfclosed.match(newsource, nsp); } return newsource; }
About::About(QWidget *parent) : QDialog(parent) { ui.setupUi(this); ui.lbHomepageDisplay->setText("<a href=\"" % SIGIL_HOMEPAGE % "\">" % SIGIL_HOMEPAGE % "</a>"); ui.lbLicenseDisplay->setText("<a href=\"" % GNU_LICENSE % "\">" % tr("GNU General Public License v3") % "</a>"); ui.lbBuildTimeDisplay->setText(GetUTCBuildTime().toString("yyyy.MM.dd HH:mm:ss") + " UTC"); ui.lbLoadedQtDisplay->setText(QString(qVersion())); QRegularExpression version_number(VERSION_NUMBERS); QRegularExpressionMatch mo = version_number.match(SIGIL_VERSION); QString version_text = QString("%1.%2.%3") .arg(mo.captured(1).toInt()) .arg(mo.captured(2).toInt()) .arg(mo.captured(3).toInt()); ui.lbVersionDisplay->setText(version_text); QString credits = "<h4>" + tr("Maintainer / Lead Developer") + "</h4>" + "<ul><li>John Schember</li></ul>" + "<h4>" + tr("Code Contributors") + "</h4>" + "<ul>" + "<li>Grant Drake</li>" + "<li>Dave Heiland</li>" + "<li>Charles King</li>" + "<li>Daniel Pavel</li>" + "<li>Grzegorz Wolszczak</li>" + "</ul>" + "<h4>" + tr("Translators") + "</h4>" + "<ul><li><a href=\"https://www.transifex.net/projects/p/sigil/\">https://www.transifex.net/projects/p/sigil/teams/</a></li></ul>" + "<h4>" + tr("Original Creator") + "</h4>" + "<ul><li>Strahinja Marković (" + tr("retired") + ")</li></ul>"; ui.creditsDisplay->setText(credits); }
void FetchThread::process(QString phost) { QUdpSocket *udpSocket ; udpSocket= new QUdpSocket(0); udpSocket->bind(QHostAddress::LocalHost, 9999); udpSocket->waitForConnected(250); QTcpSocket socket; socket.connectToHost("localhost", 4949); socket.waitForConnected(500); while (socket.waitForReadyRead(250)); QString t_hello = socket.readAll(); qDebug() << "READ: " << t_hello; socket.write(QString("list\n").toStdString().c_str() ); while (socket.waitForReadyRead(250)); QString buf1 = socket.readAll(); qDebug() << "READ: " << buf1; QStringList list_probe = buf1.split(QRegExp("\\s+")); for (int z=0; z< list_probe.size(); z++) { QString probe=list_probe.at(z); QString cmd = QString("fetch ").append(probe).append("\n"); qDebug() << "cmd : " << cmd; socket.write(cmd.toStdString().c_str() ); while (socket.waitForReadyRead(250)); QString buf2 = socket.readAll(); qDebug() << "Rep fetch :" << buf2 << "\n"; QRegularExpression re("(\\w+).(\\w+) ([0-9.]+)\\n"); QRegularExpressionMatchIterator i = re.globalMatch(buf2); re.setPatternOptions(QRegularExpression::MultilineOption); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); QString s_metric = match.captured(1); QString s_value = match.captured(3); QString s_mtr = "monit2influxdb,metric="+probe + "_" + s_metric + ",host=" + phost+ " value=" + s_value + " " + QString::number(1000000* QDateTime::currentMSecsSinceEpoch()); qDebug() << "metric: " << s_mtr.toLower(); udpSocket->writeDatagram(s_mtr.toStdString().c_str(), QHostAddress::LocalHost, 9999); } udpSocket->close(); } }
QTextList *tryReadList(QTextList *list, const QString &line) { QTextList *listOut = list; QRegularExpression exp("^( *)(\\d+\\.|\\*) (.*)$"); QRegularExpressionMatch match = exp.match(line); if (match.hasMatch()) { const int indent = match.captured(1).size() / 2 + 1; const QString contents = match.captured(3); const bool ordered = match.captured(2) != "*"; QTextListFormat fmt; fmt.setStyle(ordered ? QTextListFormat::ListDecimal : QTextListFormat::ListDisc); fmt.setIndent(indent); if (!listOut || fmt != listOut->format()) { listOut = cursor.insertList(fmt); } else { cursor.insertBlock(); } readInlineText(contents); listOut->add(cursor.block()); return listOut; } else { return 0; } }
void WebUploader::GetArenaCards(QString &html) { //Ejemplo html //<li><a href='#deck' data-toggle='tab'>Cards: List & Info</a></li> if(html.contains("<li><a href='#deck' data-toggle='tab'>Cards: List & Info</a></li>")) { deckInWeb = true; emit newWebDeckCardList(); qDebug() << "WebUploader: "<< "Inicio leer deck."; //Ejemplo html carta //<li id='374' class='list-group-item' data-name='1' data-cost='3' data-total='1' data-remaining='1' data-any='1'> //<span style='display: inline-block;'>(3) <a href='http://www.hearthpwn.com/cards/428' onClick='return false;'>Acolyte of Pain</a> //</span> (<span id='remaining-374' style='font-weight:bold;'>1</span> copy)</li> QRegularExpression re( "<li id='\\d+' class='list-group-item' data-name='\\d+' data-cost='\\d+' data-total='(\\d+)' data-remaining='\\d+' data-any='\\d+'>" "<span style='display: inline-block;'>.*<a href=.*onClick=.*>(.+)</a> " "</span>.*</li>"); QRegularExpressionMatchIterator reIterator = re.globalMatch(html); while (reIterator.hasNext()) { QRegularExpressionMatch match = reIterator.next(); emit newDeckCard(codeFromName(match.captured(2)), match.captured(1).toInt()); } qDebug() << "WebUploader: "<< "Final leer deck."; emit sendLog(tr("Web: Active deck read.")); } }
QFont stringToFont(const QString& font) { QFontDatabase fdb; QString fontFamily; int familyIdx=-1; QStringList allFamilies = fdb.families(); for(int idx=font.indexOf(' '); idx<font.size() && idx>=0; idx=font.indexOf(' ', idx+1)) { QString testFont = font.left(idx); if(allFamilies.contains(testFont)) { fontFamily = testFont; familyIdx = idx; } } QFont f; f.setFamily(fontFamily); QRegularExpression fontRx(QStringLiteral(" (.*) +([0-9]+)$")); QRegularExpressionMatch match = fontRx.match(font, familyIdx); if (match.isValid()) { QString fontStyle = match.captured(1).trimmed(); int fontSize = match.captured(2).toInt(); f.setStyleName(fontStyle); f.setPointSize(fontSize); } else { qWarning() << "Couldn't figure out syle and size" << font; } return f; }
bool parse_txt_file(const QString &inputFile, visitors::map_QStringQString &strings) { QFile iFile(inputFile); iFile.open(QFile::ReadOnly|QFile::Text); QTextStream txts(&iFile); txts.setCodec("UTF-8"); const QString rgxp("^(?<id>\\[\\[\\[[A-F0-9]{8}\\]\\]\\])\\s*[\\\",“,”](?<text>.*)[\\\",“,”]$"); QRegularExpression rxp(rgxp); unsigned int line_counter = 0; while(!txts.atEnd()) { QString str = txts.readLine(); QRegularExpressionMatch rm = rxp.match(str); QString id = rm.captured("id"); QString text = rm.captured("text"); if(id.isEmpty() || text.isEmpty()) { std::cerr << "Error in line: " << line_counter << " file: " << inputFile.toStdString().c_str() << std::endl; return false; } strings.insert(visitors::map_QStringQString::value_type(id, text)); } return true; }
void QgsProcessingUtils::parseDestinationString( QString &destination, QString &providerKey, QString &uri, QString &layerName, QString &format, QMap<QString, QVariant> &options, bool &useWriter, QString &extension ) { extension.clear(); QRegularExpression splitRx( QStringLiteral( "^(.{3,}?):(.*)$" ) ); QRegularExpressionMatch match = splitRx.match( destination ); if ( match.hasMatch() ) { providerKey = match.captured( 1 ); if ( providerKey == QStringLiteral( "postgis" ) ) // older processing used "postgis" instead of "postgres" { providerKey = QStringLiteral( "postgres" ); } uri = match.captured( 2 ); if ( providerKey == QLatin1String( "ogr" ) ) { QgsDataSourceUri dsUri( uri ); if ( !dsUri.database().isEmpty() ) { if ( !dsUri.table().isEmpty() ) { layerName = dsUri.table(); options.insert( QStringLiteral( "layerName" ), layerName ); } uri = dsUri.database(); extension = QFileInfo( uri ).completeSuffix(); format = QgsVectorFileWriter::driverForExtension( extension ); } else { extension = QFileInfo( uri ).completeSuffix(); } options.insert( QStringLiteral( "update" ), true ); } useWriter = false; } else { useWriter = true; providerKey = QStringLiteral( "ogr" ); QRegularExpression splitRx( QStringLiteral( "^(.*)\\.(.*?)$" ) ); QRegularExpressionMatch match = splitRx.match( destination ); if ( match.hasMatch() ) { extension = match.captured( 2 ); format = QgsVectorFileWriter::driverForExtension( extension ); } if ( format.isEmpty() ) { format = QStringLiteral( "GPKG" ); destination = destination + QStringLiteral( ".gpkg" ); } options.insert( QStringLiteral( "driverName" ), format ); uri = destination; } }
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 }
QDateTime About::GetUTCBuildTime() { QString time_string = QString::fromLatin1(__TIME__); QString date_string = QString::fromLatin1(__DATE__); Q_ASSERT(!date_string.isEmpty()); Q_ASSERT(!time_string.isEmpty()); QRegularExpression date_match("(\\w{3})\\s+(\\d+)\\s+(\\d{4})"); QRegularExpressionMatch mo = date_match.match(date_string); QDate date(mo.captured(3).toInt(), MonthIndexFromString(mo.captured(1)), mo.captured(2).toInt()); return QDateTime(date, QTime::fromString(time_string, "hh:mm:ss")).toUTC(); }
GameResult WebUploader::createGameResult(const QRegularExpressionMatch &match, const QString &arenaCurrentHero) { GameResult gameResult; gameResult.playerHero = arenaCurrentHero; gameResult.enemyHero = Utility::heroToLogNumber(match.captured(3)); gameResult.isFirst = match.captured(4).startsWith("P"); gameResult.isWinner = match.captured(1).startsWith("s"); return gameResult; }
void BaiduMusic::searchReplyFinished() { QString url = searchReply->request().url().toString(); int keywordBegin = url.indexOf("key=") + 4; int keywordEnd = url.indexOf("&start="); int pageBeginPos = url.indexOf("start=") + 6; int pageEndPos = url.indexOf("&size="); //当前页 int currentPage = url.mid(pageBeginPos,pageEndPos-pageBeginPos).toInt()/PAGESIZE + 1; //关键字 QString keyword = url.mid(keywordBegin,keywordEnd-keywordBegin); if(searchReply->error()){ //如果出错,pageCount为-1; emit searchComplete(currentPage,1,keyword,"{error:"+searchReply->errorString()+"}"); return; } //TODO:未搜索到内容的判断 QString html = searchReply->readAll(); QStringList songList; QRegularExpression re("<li data-songitem = '(.+?)'"); QRegularExpressionMatchIterator i = re.globalMatch(html); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); QString songData = match.captured(1); //" 替换为 " ;删除<em>和</em> songData = songData.replace(""","\"").replace("<em>","").replace("<\\/em>",""); songList << songData; } //构造json数组 QString songArray = "[" + songList.join(",") + "]"; QString result = unifyResult(songArray); //匹配总页数 QRegularExpression pageCountRe("\">(\\d+)</a>\\s*<a class=\"page-navigator-next\""); QRegularExpressionMatch match = pageCountRe.match(html); //页面总数 int pageCount = match.captured(1).toInt(); //如果没有 pageCount,则 pageCount 设为 1; pageCount = pageCount>0 ? pageCount : 1; emit searchComplete(currentPage,pageCount,keyword,result); }
QPair<QString, QString> UpdateItem::parseAnchor(const QString &input) { QPair<QString, QString> ret; QRegularExpressionMatch match = AnchorReg.match(input); if (match.hasMatch()) { ret.first = match.captured("href"); ret.second = match.captured("content"); } return ret; }
// The actual generation engine QString ShopTemplateManager::Generate(const Items &items) { QString temp = shopTemplate; { QRegularExpression expr("{(?<key>.+?)(?<options>(\\|(.+?))*?)}"); QRegularExpressionMatchIterator matcher = expr.globalMatch(shopTemplate); int offset = 0; while (matcher.hasNext()) { QRegularExpressionMatch match = matcher.next(); QString key = match.captured("key").toLower(); int startPos = offset + match.capturedStart(); int len = match.capturedLength(); QStringList optionsAndData = match.captured("options").split("|", QString::SkipEmptyParts); QHash<QString, QString> options; for (QString optionAndData : optionsAndData) { int split = optionAndData.indexOf(":"); if (split == -1) { options.insert(optionAndData.toLower(), ""); } else { QString option = optionAndData.left(split).toLower(); QString data = optionAndData.mid(split + 1); options.insert(option, data); } } QString replacement = FetchFromKey(key, items, &options); temp.replace(startPos, len, replacement); offset += replacement.length() - len; } } // Now clean up empty spoiler tags! int matches = -1; while (matches != 0){ QRegularExpression expr("\\[spoiler=\\\"(?>.*?\\\"\\])(?>\\s*?\\[\\/spoiler\\]\\n)"); QRegularExpressionMatchIterator matcher = expr.globalMatch(temp); int offset = 0; matches = 0; while (matcher.hasNext()) { QRegularExpressionMatch match = matcher.next(); int startPos = match.capturedStart() + offset; int length = match.capturedLength(); temp.remove(startPos, length); offset -= length; matches++; } } return temp; }
void Template::translate(ITemplateTranslationProvider &provider) { //This regex captures expressions of the form //<?= tr("This is a test") ?> and <?= tr("optional %1 parameters %2","bla","blu") ?> //The first capture group is the key (untranslated string), the second the optional list of parameters const QRegularExpression regexp = QRegularExpression("<\\?=\\s*tr\\(\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"((?:,\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")*)\\s*\\)\\?>"); //This one is used to extract the parameters using global matching const QRegularExpression paramExp = QRegularExpression(",\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\""); int offset = 0; QRegularExpressionMatch match; do { match = regexp.match(*this,offset); if(match.hasMatch()) { int start = match.capturedStart(0); int len = match.capturedLength(0); QString key = match.captured(1); //replace escaped double and single quotes key.replace("\\\"","\""); key.replace("\\'", "'"); QString translation = provider.getTranslation(key); //find out if we have optional parameters if(match.capturedLength(2)>0) { QString params = match.captured(2); //extract each optional parameter QRegularExpressionMatchIterator it = paramExp.globalMatch(params); while(it.hasNext()) { QRegularExpressionMatch paramMatch = it.next(); QString param = paramMatch.captured(1); //replace escaped quotes param.replace("\\\"","\""); param.replace("\\'", "'"); //apply the param translation = translation.arg(param); } } this->replace(start,len,translation); offset = start+translation.length(); } }while(match.hasMatch()); }
/** * Load a palette from a GIMP palette file. * * The file format is: * * GIMP Palette * *HEADER FIELDS* * # one or more comment * r g b name * ... * * @param filename palette file name * @param writeprotected is the source file read only */ Palette *Palette::fromFile(const QFileInfo& file, bool readonly, QObject *parent) { QFile palfile(file.absoluteFilePath()); if (!palfile.open(QIODevice::ReadOnly | QIODevice::Text)) return nullptr; QTextStream in(&palfile); if(in.readLine() != "GIMP Palette") return nullptr; Palette *pal = new Palette(file.baseName(), file.absoluteFilePath(), !file.isWritable() | readonly, parent); const QRegularExpression colorRe("^(\\d+)\\s+(\\d+)\\s+(\\d+)\\s*(.+)?$"); do { QString line = in.readLine().trimmed(); if(line.isEmpty() || line.at(0) == '#') { // ignore comments and empty lines } else if(line.startsWith("Name:")) { pal->_name = line.mid(5).trimmed(); } else if(line.startsWith("Columns:")) { bool ok; int cols = line.mid(9).trimmed().toInt(&ok); if(ok && cols>0) pal->_columns = cols; } else { QRegularExpressionMatch m = colorRe.match(line); if(m.hasMatch()) { pal->_colors.append(PaletteColor( QColor( m.captured(1).toInt(), m.captured(2).toInt(), m.captured(3).toInt() ), m.captured(4) ) ); } else { qWarning() << "unhandled line" << line << "in" << file.fileName(); } } } while(!in.atEnd()); // Palettes loaded from file are write-protected by default pal->_writeprotect = true; return pal; }
bool QGCAudioWorker::_getMillisecondString(const QString& string, QString& match, int& number) { static QRegularExpression re("([0-9]+ms)"); QRegularExpressionMatchIterator i = re.globalMatch(string); while (i.hasNext()) { QRegularExpressionMatch qmatch = i.next(); if (qmatch.hasMatch()) { match = qmatch.captured(0); number = qmatch.captured(0).replace("ms", "").toInt(); return true; } } return false; }
QStringList CaViewerScanner::getImageSeries(QString sPath, QString sFileName, QString &sRetBaseName) { // creates list components based on sFilename (eg. .../foo_t0001.tif) QStringList slImageSeries; // checks whether the filename matches the format or not const QString sFormatPrefix("^(?<name>.+)"); const QString sFormatNumber("_t(?<num>\\d{4})"); const QString sFormatSuffix("(?<dotext>\\..{1,3})$"); const QRegularExpression regexpSeries(sFormatPrefix + sFormatNumber + sFormatSuffix); const QRegularExpressionMatch matchSeries = regexpSeries.match(sFileName); if(matchSeries.hasMatch()) { // match found (i.e. there are related files in the same folder) sRetBaseName = matchSeries.captured("name"); const QString sExtension = matchSeries.captured("dotext"); const QDir dir(sPath); const QStringList slAllFiles = dir.entryList(QDir::Files, QDir::Name); QRegularExpression regexpFileName(QRegularExpression::escape(sRetBaseName) + sFormatNumber + QRegularExpression::escape(sExtension)); int nSequence = 0; for(int count = 0; count < slAllFiles.size(); ++count) { QRegularExpressionMatch match = regexpFileName.match(slAllFiles.at(count)); if(match.hasMatch()) { int fileNum = match.captured("num").toInt(); if(fileNum != nSequence) return slImageSeries; else { slImageSeries << slAllFiles.at(count); ++nSequence; } } } } else { // no match found const QRegularExpression regexpSingle(sFormatPrefix + sFormatSuffix); const QRegularExpressionMatch matchSingle = regexpSingle.match(sFileName); if(matchSingle.hasMatch()) { sRetBaseName = matchSingle.captured("name"); slImageSeries << sFileName; } } return slImageSeries; }
bool QLinuxFbScreen::initialize() { QRegularExpression ttyRx(QLatin1String("tty=(.*)")); QRegularExpression fbRx(QLatin1String("fb=(.*)")); QRegularExpression mmSizeRx(QLatin1String("mmsize=(\\d+)x(\\d+)")); QRegularExpression sizeRx(QLatin1String("size=(\\d+)x(\\d+)")); QRegularExpression offsetRx(QLatin1String("offset=(\\d+)x(\\d+)")); QString fbDevice, ttyDevice; QSize userMmSize; QRect userGeometry; bool doSwitchToGraphicsMode = true; // Parse arguments foreach (const QString &arg, mArgs) { QRegularExpressionMatch match; if (arg == QLatin1String("nographicsmodeswitch")) doSwitchToGraphicsMode = false; else if (arg.contains(mmSizeRx, &match)) userMmSize = QSize(match.captured(1).toInt(), match.captured(2).toInt()); else if (arg.contains(sizeRx, &match)) userGeometry.setSize(QSize(match.captured(1).toInt(), match.captured(2).toInt())); else if (arg.contains(offsetRx, &match)) userGeometry.setTopLeft(QPoint(match.captured(1).toInt(), match.captured(2).toInt())); else if (arg.contains(ttyRx, &match)) ttyDevice = match.captured(1); else if (arg.contains(fbRx, &match)) fbDevice = match.captured(1); }
bool RawHtmlPostprocessor::isblocklevel(const QString &html) { QRegularExpressionMatch m = QRegularExpression("^\\<\\/?([^ >]+)").match(html); if ( m.hasMatch() ) { QChar ch = m.captured(1).at(0); // SPECIAL_CHARS: !, ?, @, % if ( SPECIAL_CHARS.contains(ch) ) { //! Comment, php etc... return true; } return util::isBlockLevel(m.captured(1)); } return false; }
/** * Called when recieving a private message. * Adds message to a tab if the tab corresponds to the given convo id, * otherwise creates a new tab. * @brief MainWindow::displayPrivateMsg * @param data "{convo_id}|{from_ip}|{message_txt}" */ void MainWindow::displayPrivateMsg(QString data) { QRegularExpression re("(\\d+)\\|(\\d+\\.\\d+\\.\\d+\\.\\d+)\\|(.*)"); QRegularExpressionMatch match = re.match(data); for (int i = 0; i < convos->count(); i++) { if(convos->at(i)->getCid().compare(match.captured(1)) == 0) { QTextEdit* tmp = ui->tabgrpConversations->widget(i+1)->findChild<QTextEdit*>(CONVO_TAB_TXT_ID); addTextToConvo(tmp, match.captured(3)); if(ui->tabgrpConversations->currentIndex() != i+1) //if tab not focused, set header color to red. indicateChange(i+1, CHANGE_NEW); if(!isVisible()) displayTrayMsg(i+1, match.captured(3)); return; } } createTab(match.captured(1), match.captured(2), match.captured(3).split("|").at(0)); QTextEdit* tmp = ui->tabgrpConversations->widget(convos->count())->findChild<QTextEdit*>(CONVO_TAB_TXT_ID); addTextToConvo(tmp, match.captured(3)); indicateChange(convos->count(), CHANGE_NEW); if(!isVisible()) displayTrayMsg(convos->count(), match.captured(3)); }
// #3: Sexagesimal bool LonLatParser::tryMatchFromDms(const QString& input, DirPosition dirPosition) { // direction as postfix const QString postfixCapExp = QStringLiteral("\\A(?:") + QStringLiteral("([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2})(?:%4|\\s)\\s*") + QStringLiteral("(\\d{1,2}%1?\\d*)(?:%5)?\\s*%2[,;]?\\s*") + QStringLiteral("([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2})(?:%4|\\s)\\s*") + QStringLiteral("(\\d{1,2}%1?\\d*)(?:%5)?\\s*%2") + QStringLiteral(")\\z"); // direction as prefix const QString prefixCapExp = QStringLiteral("\\A(?:") + QStringLiteral("%2\\s*([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2})(?:%4|\\s)\\s*") + QStringLiteral("(\\d{1,2}%1?\\d*)(?:%5)?\\s*(?:,|;|\\s)\\s*") + QStringLiteral("%2\\s*([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2})(?:%4|\\s)\\s*") + QStringLiteral("(\\d{1,2}%1?\\d*)(?:%5)?") + QStringLiteral(")\\z"); const QString &expTemplate = (dirPosition == PostfixDir) ? postfixCapExp : prefixCapExp; const QString numberCapExp = expTemplate.arg(m_decimalPointExp, m_dirCapExp, m_degreeExp, m_minutesExp, m_secondsExp); const QRegularExpression regex(numberCapExp); QRegularExpressionMatch match = regex.match(input); if (!match.hasMatch()) { return false; } bool isDir1LonDir; bool isLonDirPosHemisphere; bool isLatDirPosHemisphere; const QString dir1 = match.captured(dirPosition == PostfixDir ? 5 : 1); const QString dir2 = match.captured(dirPosition == PostfixDir ? 10 : 6); if (!isCorrectDirections(dir1, dir2, isDir1LonDir, isLonDirPosHemisphere, isLatDirPosHemisphere)) { return false; } const int valueStartIndex1 = (dirPosition == PostfixDir ? 1 : 2); const int valueStartIndex2 = (dirPosition == PostfixDir ? 6 : 7); m_lon = degreeValueFromDMS(match, isDir1LonDir ? valueStartIndex1 : valueStartIndex2, isLonDirPosHemisphere); m_lat = degreeValueFromDMS(match, isDir1LonDir ? valueStartIndex2 : valueStartIndex1, isLatDirPosHemisphere); return true; }
QStringList EpisodeFinder::getEpisodes(const QString &seasonPath, int season, int episode) const { QDir seasonDir(seasonPath); QMimeDatabase db; QStringList files; foreach (const QFileInfo &fileInfo, seasonDir.entryInfoList()) { if (!fileInfo.isFile()) continue; QMimeType mimeType = db.mimeTypeForFile(fileInfo); // must have got a video mime type if (!mimeType.name().startsWith("video/")) continue; if (season == -1) { files << fileInfo.absoluteFilePath(); continue; } QString fileName = fileInfo.fileName(); int fileSeason, fileEpisode; // SXXEXX expression? QRegularExpression re("\\bS([0-9]+)E([0-9]+)", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatch match = re.match(fileName); if (match.hasMatch()) { fileSeason = match.captured(1).toInt(); fileEpisode = match.captured(2).toInt(); if (fileSeason == season && fileEpisode == episode) files << fileInfo.absoluteFilePath(); continue; } // SxE expression? re.setPattern("\\b([0-9]+)x([0-9]+)"); match = re.match(fileName); if (match.hasMatch()) { fileSeason = match.captured(1).toInt(); fileEpisode = match.captured(2).toInt(); if (fileSeason == season && fileEpisode == episode) files << fileInfo.absoluteFilePath(); continue; } } return files; }
void GnuMakeParser::stdOutput(const QString &line) { const QString lne = rightTrimmed(line); QRegularExpressionMatch match = m_makeDir.match(lne); if (match.hasMatch()) { if (match.captured(6) == QLatin1String("Leaving")) removeDirectory(match.captured(7)); else addDirectory(match.captured(7)); return; } IOutputParser::stdOutput(line); }
QStringList EpisodeFinder::getSubtitles(const QString &seasonPath, int season, int episode) const { QDir seasonDir(seasonPath); QMimeDatabase db; QStringList files; foreach (const QFileInfo &fileInfo, seasonDir.entryInfoList()) { if (!fileInfo.isFile()) continue; // must be a subtitle if (subtitleExtensions.indexOf(fileInfo.suffix().toLower()) < 0) continue; if (season == -1) { files << fileInfo.absoluteFilePath(); continue; } QString fileName = fileInfo.fileName(); int fileSeason, fileEpisode; // SXXEXX expression? QRegularExpression re("\\bS([0-9]+)E([0-9]+)", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatch match = re.match(fileName); if (match.hasMatch()) { fileSeason = match.captured(1).toInt(); fileEpisode = match.captured(2).toInt(); if (fileSeason == season && (fileEpisode == episode || episode == -1)) files << fileInfo.absoluteFilePath(); continue; } // SxE expression? re.setPattern("\\b([0-9]+)x([0-9]+)"); match = re.match(fileName); if (match.hasMatch()) { fileSeason = match.captured(1).toInt(); fileEpisode = match.captured(2).toInt(); if (fileSeason == season && (fileEpisode == episode || episode == -1)) files << fileInfo.absoluteFilePath(); continue; } } return files; }