///Obtain all regex matches in a std::string //From http://www.richelbilderbeek.nl/CppGetRegexMatches.htm const std::vector<std::string> ribi::RegexTesterQtMainDialog::GetRegexMatches( const std::string& s, const QRegExp& r_original) { QRegExp r = r_original; r.setMinimal(true); //QRegExp must be non-greedy std::vector<std::string> v; int pos = 0; while ((pos = r.indexIn(s.c_str(), pos)) != -1) { const QString q = r.cap(1); if (q.isEmpty()) break; v.push_back(q.toStdString()); pos += r.matchedLength(); } return v; }
static QString resolvedReplacement( const QString &replacement, const QRegExp &expr ) { //qDebug("START"); static const QRegExp rexpr("(\\\\\\\\)|(\\\\[0-9]+)"); QString str( replacement ); int i=0; while(i < str.size() && ((i = rexpr.indexIn(str, i)) != -1)) { int len = rexpr.matchedLength(); if(rexpr.pos(1) != -1) { //qDebug("%i (%s): escape", i, CSTR(rexpr.cap(1))); str.replace(i, len, "\\"); i += 1; } else if(rexpr.pos(2) != -1) { QString num_str = rexpr.cap(2); num_str.remove(0, 1); int num = num_str.toInt(); //qDebug("%i (%s): backref = %i", i, CSTR(rexpr.cap(2)), num); if(num <= expr.captureCount()) { QString cap = expr.cap(num); //qDebug("resolving ref to: %s", CSTR(cap)); str.replace(i, len, cap); i += cap.size(); } else { //qDebug("ref out of range", i, num); str.remove(i, len); } } else { //qDebug("%i (%s): unknown match", i, CSTR(rexpr.cap(0))); str.remove(i, len); } //qDebug(">> [%s] %i", CSTR(str), i); } //qDebug("END"); return str; }
void HttpConnection::translateDocument(QString& data) { static QRegExp regex(QString::fromUtf8("_\\(([\\w\\s?!:\\/\\(\\),%µ&\\-\\.]+)\\)")); static QRegExp mnemonic("\\(?&([a-zA-Z]?\\))?"); const std::string contexts[] = {"TransferListFiltersWidget", "TransferListWidget", "PropertiesWidget", "MainWindow", "HttpServer", "confirmDeletionDlg", "TrackerList", "TorrentFilesModel", "options_imp", "Preferences", "TrackersAdditionDlg", "ScanFoldersModel", "PropTabBar", "TorrentModel", "downloadFromURL", "misc"}; const size_t context_count = sizeof(contexts)/sizeof(contexts[0]); int i = 0; bool found = true; const QString locale = Preferences().getLocale(); bool isTranslationNeeded = !locale.startsWith("en") || locale.startsWith("en_AU") || locale.startsWith("en_GB"); while(i < data.size() && found) { i = regex.indexIn(data, i); if (i >= 0) { //qDebug("Found translatable string: %s", regex.cap(1).toUtf8().data()); QByteArray word = regex.cap(1).toUtf8(); QString translation = word; if (isTranslationNeeded) { int context_index = 0; while(context_index < context_count && translation == word) { #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) translation = qApp->translate(contexts[context_index].c_str(), word.constData(), 0, QCoreApplication::UnicodeUTF8, 1); #else translation = qApp->translate(contexts[context_index].c_str(), word.constData(), 0, 1); #endif ++context_index; } } // Remove keyboard shortcuts translation.replace(mnemonic, ""); data.replace(i, regex.matchedLength(), translation); i += translation.length(); } else { found = false; // no more translatable strings } } }
bool PerforceParser::parseContextDiffHeader() { // qCDebug(LIBKOMPAREDIFF2) << "ParserBase::parseContextDiffHeader()"; bool result = false; QStringList::ConstIterator itEnd = m_diffLines.end(); QRegExp sourceFileRE ( "([^\\#]+)#(\\d+)" ); QRegExp destinationFileRE( "([^\\#]+)#(|\\d+)" ); while ( m_diffIterator != itEnd ) { if ( m_contextDiffHeader1.exactMatch( *(m_diffIterator)++ ) ) { // qCDebug(LIBKOMPAREDIFF2) << "Matched length Header1 = " << m_contextDiffHeader1.matchedLength(); // qCDebug(LIBKOMPAREDIFF2) << "Matched string Header1 = " << m_contextDiffHeader1.cap( 0 ); // qCDebug(LIBKOMPAREDIFF2) << "First capture Header1 = " << m_contextDiffHeader1.cap( 1 ); // qCDebug(LIBKOMPAREDIFF2) << "Second capture Header1 = " << m_contextDiffHeader1.cap( 2 ); m_currentModel = new DiffModel(); sourceFileRE.exactMatch( m_contextDiffHeader1.cap( 1 ) ); destinationFileRE.exactMatch( m_contextDiffHeader1.cap( 2 ) ); qCDebug(LIBKOMPAREDIFF2) << "Matched length = " << sourceFileRE.matchedLength(); qCDebug(LIBKOMPAREDIFF2) << "Matched length = " << destinationFileRE.matchedLength(); qCDebug(LIBKOMPAREDIFF2) << "Captured texts = " << sourceFileRE.capturedTexts(); qCDebug(LIBKOMPAREDIFF2) << "Captured texts = " << destinationFileRE.capturedTexts(); qCDebug(LIBKOMPAREDIFF2) << "Source File : " << sourceFileRE.cap( 1 ); qCDebug(LIBKOMPAREDIFF2) << "Destination File : " << destinationFileRE.cap( 1 ); m_currentModel->setSourceFile ( sourceFileRE.cap( 1 ) ); m_currentModel->setDestinationFile( destinationFileRE.cap( 1 ) ); result = true; break; } else { qCDebug(LIBKOMPAREDIFF2) << "Matched length = " << m_contextDiffHeader1.matchedLength(); qCDebug(LIBKOMPAREDIFF2) << "Captured texts = " << m_contextDiffHeader1.capturedTexts(); } } return result; }
bool Project::setFilePath(const QString &filePath) { static const QRegExp rx("/\\*\\s+QssEditor:\\s+([a-zA-Z0-9+\\/=]+)\\s+\\*/\\s+"); m_error.clear(); if(filePath.isEmpty()) { m_error = QObject::tr("File name is empty"); return false; } QFile file(filePath); if(!file.open(QIODevice::ReadOnly)) { m_error = file.errorString(); return false; } QString qss = file.readAll(); int version = -1; file.close(); if(rx.indexIn(qss) == 0) { QByteArray ba = QByteArray::fromBase64(rx.cap(1).toLatin1()); QDataStream ds(&ba, QIODevice::ReadOnly); ds.setVersion(QDataStream::Qt_4_0); ds >> version; if(ds.status() != QDataStream::Ok) { m_error = dataStreamErrorToString(ds.status()); return false; } qss = qss.mid(rx.matchedLength()); qDebug("Loaded project version %d", version); }
QString LiteEditorWidget::textUnderCursor(QTextCursor tc) const { QString text = tc.block().text().left(tc.positionInBlock()); if (text.isEmpty()) { return QString(); } //int index = text.lastIndexOf(QRegExp("\\b[a-zA-Z_][a-zA-Z0-9_\.]+")); static QRegExp reg("[a-zA-Z_\\.]+[a-zA-Z0-9_\\.]*$"); int index = reg.indexIn(text); if (index < 0) { return QString(); } return text.right(reg.matchedLength()); //int index = text.lastIndexOf(QRegExp("[\w]+$")); // qDebug() << ">" << text << index; // int left = text.lastIndexOf(QRegExp("[ |\t|\"|\(|\)|\'|<|>]")); // text = text.right(text.length()-left+1); return ""; }
VariableList_t* PHPVariableParser::parseArray(PHPVariable* var) { int size; VariableList_t* list = new VariableList_t; QRegExp rx; rx.setPattern("a:(\\d*):\\{"); if(rx.search(m_raw, m_index) == -1) return list; size = rx.cap(1).toInt(); m_index += rx.matchedLength(); for(int i = 0; i < size; i++) { list->append(parseVarName(var)); } m_index++; //eats the '}' return list; }
bool BaseObject::isCodeDiffersFrom(const QString &xml_def1, const QString &xml_def2, const vector<QString> &ignored_attribs, const vector<QString> &ignored_tags) { QString xml, tag=QString("<%1").arg(this->getSchemaName()), attr_regex=QString("(%1=\")"), tag_regex=QString("<%1[^>]*((/>)|(>((?:(?!</%1>).)*)</%1>))"); QStringList xml_defs{ xml_def1, xml_def2 }; int start=0, end=-1, tag_end=-1; QRegExp regexp; for(int i=0; i < 2; i++) { xml=xml_defs[i].simplified(); start=xml.indexOf(tag) + tag.length(); end=-1; //Removing ignored attributes for(QString attr : ignored_attribs) { do { regexp=QRegExp(attr_regex.arg(attr)); tag_end=xml.indexOf(QRegExp(QString("(\\\\)?(>)"))); start=regexp.indexIn(xml);//, start); end=xml.indexOf('"', start + regexp.matchedLength()); if(end > tag_end) end=-1; if(start >=0 && end >=0) xml.remove(start, (end - start) + 1); } while(start >= 0 && end >= 0); } //Removing ignored tags for(QString tag : ignored_tags) xml.remove(QRegExp(tag_regex.arg(tag))); xml_defs[i]=xml.simplified(); } return(xml_defs[0]!=xml_defs[1]); }
QString CodeConverterBase::replaceFunctionInvocations(QString const &expression) const { QString result = expression; QString const randomTemplate = mFunctionInvocationsConverter->convert("random"); QRegExp const randomFunctionInvocationRegEx("random\\((.*)\\)"); int pos = randomFunctionInvocationRegEx.indexIn(result, 0); while (pos != -1) { QString const param = randomFunctionInvocationRegEx.cap(1); QString randomInvocation = randomTemplate; randomInvocation.replace("@@UPPER_BOUND@@", param); result.replace(randomFunctionInvocationRegEx, randomInvocation); pos += randomFunctionInvocationRegEx.matchedLength(); pos = randomFunctionInvocationRegEx.indexIn(result, pos); } return result; }
void Resolver::resolve(QString& inStr, QString& outStr) { QRegExp rx ("[\"'](http://(.+))[\"']"); rx.setMinimal(true); inStr.replace(QRegExp("[\\r\\n]"), " "); QTextStream stream(&inStr); QString line; sqlite3_stmt* ppStmt; while((line = stream.readLine()) != 0) { int pos = 0; while ((pos = rx.indexIn(line, pos)) != -1) { QString url = rx.cap(2); url.replace('/', "_"); QString fname(CacheDir + url); if(!QFile::exists(fname)) { QFile fd(fname); if(!_db->query(QString("SELECT data FROM http WHERE url = '") + rx.cap(2) + QString("'"))) qFatal("TODO #3 Resolver"); if((ppStmt = _db->next()) != 0) { fd.open(QIODevice::WriteOnly); const void* data = sqlite3_column_blob(ppStmt, 0); int size = sqlite3_column_bytes(ppStmt, 0); QByteArray ba(static_cast<const char*>(data), size); fd.write(ba); fd.close(); } else fname = _uFileName; } line.replace(rx.cap(1), fname); pos += rx.matchedLength(); } outStr += line; } }
void MercurialSubmitHighlighter::highlightBlock(const QString &text) { // figure out current state State state = static_cast<State>(previousBlockState()); if (text.startsWith(QLatin1String("HG:"))) { setFormat(0, text.size(), formatForCategory(Format_Comment)); setCurrentBlockState(state); return; } if (state == None) { if (text.isEmpty()) { setCurrentBlockState(state); return; } state = Header; } else if (state == Header) { state = Other; } setCurrentBlockState(state); // Apply format. switch (state) { case None: break; case Header: { QTextCharFormat charFormat = format(0); charFormat.setFontWeight(QFont::Bold); setFormat(0, text.size(), charFormat); break; } case Other: // Format key words ("Task:") italic if (m_keywordPattern.indexIn(text, 0, QRegExp::CaretAtZero) == 0) { QTextCharFormat charFormat = format(0); charFormat.setFontItalic(true); setFormat(0, m_keywordPattern.matchedLength(), charFormat); } break; } }
VariableList_t* PHPVariableParser::parseObjectMembers(PHPVariable* parent) { //O:6:"Classe":3:{s:6:"membro";N;s:4:"mem2";N;s:4:"priv";N;} int size; VariableList_t* list = new VariableList_t; QRegExp rx; rx.setPattern("(\\d*):\\{"); if(rx.search(m_raw, m_index) == -1) return list; size = rx.cap(1).toInt(); m_index += rx.matchedLength(); for(int i = 0; i < size; i++) { list->append(parseVarName(parent)); } m_index++; //eats the '}' return list; }
void SpellHighlighter::highlightBlock(const QString &AText) { if (FEnabled) { // Match words (minimally) excluding digits within a word static const QRegExp expression("\\b[^\\s\\d]+\\b"); int index = 0; while ((index = expression.indexIn(AText, index)) != -1) { int length = expression.matchedLength(); if (!isUserNickName(expression.cap())) { if (!SpellBackend::instance()->isCorrect(expression.cap())) setFormat(index, length, FCharFormat); } index += length; } } }
void SearchWhileTyping::startSearch(const KTextEditor::Document *doc, const QRegExp ®Exp) { int column; QTime maxTime; maxTime.start(); for (int line =0; line < doc->lines(); line++) { if (maxTime.elapsed() > 50) { kDebug() << "Search time exceeded -> stop" << maxTime.elapsed() << line; break; } column = regExp.indexIn(doc->line(line)); while (column != -1) { emit matchFound(doc->url().pathOrUrl(), line, column, doc->line(line), regExp.matchedLength()); column = regExp.indexIn(doc->line(line), column + 1); } } emit searchDone(); }
// Simplify string types in a type // 'std::set<std::basic_string<char... > >' -> std::set<std::string>' static inline void simplifyStdString(const QString &charType, const QString &replacement, QString *type) { QRegExp stringRegexp = stdStringRegExp(charType); const int replacementSize = replacement.size(); for (int pos = 0; pos < type->size(); ) { // Check next match const int matchPos = stringRegexp.indexIn(*type, pos); if (matchPos == -1) break; const int matchedLength = stringRegexp.matchedLength(); type->replace(matchPos, matchedLength, replacement); pos = matchPos + replacementSize; // If we were inside an 'allocator<std::basic_string..char > >' // kill the following blank -> 'allocator<std::string>' if (pos + 1 < type->size() && type->at(pos) == QLatin1Char(' ') && type->at(pos + 1) == QLatin1Char('>')) type->remove(pos, 1); } }
QSqlQuery Application::execSql(const QString &query_str) { QString qs = query_str; { static QRegExp rx_id_placeholders("\\{\\{([A-Za-z0-9\\.\\_\\/]+)\\}\\}"); int pos = 0; while((pos = rx_id_placeholders.indexIn(query_str, pos)) != -1) { QString fld_name = rx_id_placeholders.cap(1); qs.replace(rx_id_placeholders.cap(0), appConfigValue(fld_name).toString()); pos += rx_id_placeholders.matchedLength(); } } QSqlDatabase db = sqlConnetion(); QSqlQuery q(db); if(!q.exec(qs)) { QSqlError err = q.lastError(); //qCritical() << ("SQL ERROR: "%err.text()); //qCritical() << ("QUERY: "%q.lastQuery()); } return q; }
int SearchOpenFiles::searchSingleLineRegExp(KTextEditor::Document *doc, const QRegExp ®Exp, int startLine) { int column; QTime time; time.start(); for (int line = startLine; line < doc->lines(); line++) { if (time.elapsed() > 100) { kDebug() << "Search time exceeded" << time.elapsed() << line; return line; } column = regExp.indexIn(doc->line(line)); while (column != -1) { if (regExp.cap().isEmpty()) break; emit matchFound(doc->url().pathOrUrl(), doc->documentName(), line, column, doc->line(line), regExp.matchedLength()); column = regExp.indexIn(doc->line(line), column + regExp.cap().size()); } } return 0; }
QSet<QString> QgsExpression::referencedVariables( const QString &text ) { QSet<QString> variables; int index = 0; while ( index < text.size() ) { QRegExp rx = QRegExp( "\\[%([^\\]]+)%\\]" ); int pos = rx.indexIn( text, index ); if ( pos < 0 ) break; index = pos + rx.matchedLength(); QString to_replace = rx.cap( 1 ).trimmed(); QgsExpression exp( to_replace ); variables.unite( exp.referencedVariables() ); } return variables; }
QString MobiDocument::fixMobiMarkup(const QString& data) { QString ret=data; QMap<int,QString> anchorPositions; static QRegExp anchors("<a(?: href=\"[^\"]*\"){0,1}[\\s]+filepos=['\"]{0,1}([\\d]+)[\"']{0,1}", Qt::CaseInsensitive); int pos=0; // find all link destinations while ( (pos=anchors.indexIn( data, pos ))!=-1) { int filepos=anchors.cap( 1 ).toUInt( ); if (filepos) anchorPositions[filepos]=anchors.cap(1); pos+=anchors.matchedLength(); } // put HTML anchors in all link destinations int offset=0; QMapIterator<int,QString> it(anchorPositions); while (it.hasNext()) { it.next(); // link pointing outside the document, ignore if ( (it.key()+offset) >= ret.size()) continue; int fixedpos=outsideTag(ret, it.key()+offset); ret.insert(fixedpos,QString("<a name=\"")+it.value()+QString("\"> </a>")); // inserting anchor shifts all offsets after the anchor offset+=21+it.value().size(); } // replace links referencing filepos with normal internal links ret.replace(anchors,"<a href=\"#\\1\""); // Mobipocket uses strange variang of IMG tags: <img recindex="3232"> where recindex is number of // record containing image static QRegExp imgs("<img.*recindex=\"([\\d]*)\".*>", Qt::CaseInsensitive); imgs.setMinimal(true); ret.replace(imgs,"<img src=\"pdbrec:/\\1\">"); ret.replace("<mbp:pagebreak/>","<p style=\"page-break-after:always\"></p>"); return ret; }
QString HtmlMangle::Anchorize (const QString &text, QRegExp regular, void (*anchorFunc)(QString&, QString)) { int where; int offset(0); int lenSub; QString newtext; QString chunk; while ((where = regular.indexIn (text,offset)) >= 0) { lenSub = regular.matchedLength(); chunk = text.mid (offset, where - offset); newtext.append (chunk); QString anchor; (*anchorFunc) (anchor, regular.cap(0)); newtext.append (anchor); offset = where + lenSub; } chunk = text.mid (offset,-1); newtext.append (chunk); return newtext; }
void HttpConnection::translateDocument(QString& data) { static QRegExp regex(QString::fromUtf8("_\\(([\\w\\s?!:\\/\\(\\),%µ&\\-\\.]+)\\)")); static QRegExp mnemonic("\\(?&([a-zA-Z]?\\))?"); const std::string contexts[] = {"TransferListFiltersWidget", "TransferListWidget", "PropertiesWidget", "MainWindow", "HttpServer", "confirmDeletionDlg", "TrackerList", "TorrentFilesModel", "options_imp", "Preferences", "TrackersAdditionDlg", "ScanFoldersModel", "PropTabBar", "TorrentModel", "downloadFromURL"}; int i = 0; bool found; do { found = false; i = regex.indexIn(data, i); if (i >= 0) { //qDebug("Found translatable string: %s", regex.cap(1).toUtf8().data()); QByteArray word = regex.cap(1).toUtf8(); QString translation = word; bool isTranslationNeeded = !Preferences().getLocale().startsWith("en"); if (isTranslationNeeded) { int context_index = 0; do { translation = qApp->translate(contexts[context_index].c_str(), word.constData(), 0, QCoreApplication::UnicodeUTF8, 1); ++context_index; } while(translation == word && context_index < 15); } // Remove keyboard shortcuts translation.replace(mnemonic, ""); data.replace(i, regex.matchedLength(), translation); i += translation.length(); found = true; } } while(found && i < data.size()); }
bool QSnippetManager::loadSnippetFromFile(const QString& file, const QString& type) { QFile f(file); if ( !f.open(QFile::ReadOnly | QFile::Text) ) { qWarning("Unable to load snippet from %s", qPrintable(file)); return false; } //qDebug("loading from : %s", qPrintable(file)); QString s = QString::fromLocal8Bit(f.readAll()); static const QRegExp meta("# name:(\\S+) context:(\\S*)[^\n]*\n"); int idx = meta.indexIn(s); bool metaMatch = idx != -1; if ( metaMatch ) { //qDebug("meta! : %i => %s", idx, qPrintable(meta.cap(0))); s.remove(idx, meta.matchedLength()); } if ( s.endsWith('\n') ) s.chop(1); bool ok = loadSnippetFromString(metaMatch ? meta.cap(1) : QFileInfo(file).baseName(), s, type); if ( ok ) { QSnippet *snip = m_snippets.last(); snip->setContexts(metaMatch ? meta.cap(2).split(",") : QStringList("all")); } return ok; }
TextUrlData TextParser::extractUrlData(const QString& text, bool doUrlFixup) { TextUrlData data; QString htmlText(text); s_urlPattern.setCaseSensitivity(Qt::CaseInsensitive); int pos = 0; int urlLen = 0; QString protocol; QString href; while ((pos = s_urlPattern.indexIn(htmlText, pos)) >= 0) { urlLen = s_urlPattern.matchedLength(); href = htmlText.mid(pos, urlLen); data.urlRanges << QPair<int, int>(pos, href.length()); pos += href.length(); if (doUrlFixup) { protocol.clear(); if (s_urlPattern.cap(2).isEmpty()) { QString urlPatternCap1(s_urlPattern.cap(1)); if (urlPatternCap1.contains(QLatin1Char('@'))) { protocol = QLatin1String("mailto:"); } else if (urlPatternCap1.startsWith(QLatin1String("ftp."), Qt::CaseInsensitive)) { protocol = QLatin1String("ftp://"); } else { protocol = QLatin1String("http://"); } } href = protocol + href; data.fixedUrls.append(href); } } return data; }
int equation_analizer::devide_on_lexem() { #if defined NM_DEBUG { ++tab_size; tab_string=""; for ( int i = 0; i<tab_size;++i ) tab_string+=" "; cout << endl << tab_string << "int equation_analizer::devide_on_lexem()" << "\t" << "start..." << endl; } #endif // QRegExp rx ( "(((\\d+\\.?\\d*)(\\[[^\\[\\]]+\\])?)|(-)|(\\+)|(\\*)|(/)|(\\()|(\\)))" ); QRegExp rx ( "(((\\d+\\.?\\d*([eE][\\+-]?\\d+)?)(\\[[^\\[\\]]+\\])?)|(-)|(\\+)|(\\*)|(/)|(\\()|(\\)))" ); int pos = 0; int i = 0; while ( ( pos = rx.indexIn ( m_equation, pos ) ) != -1 ) { ++i; m_lexem_lst << rx.cap ( 1 ); pos += rx.matchedLength(); } #if defined NM_DEBUG { tab_string=""; for ( int i = 0; i<tab_size;++i ) tab_string+=" "; cout << endl << tab_string << "int equation_analizer::devide_on_lexem()" << "\t" << "ended." << endl; --tab_size; } #endif return i; }
void LuaSyntaxHighlighter::colorizeSingleLine(const QString &text, QTextCharFormat &tokenFormat, QRegExp startExpression, QRegExp endExpression) { int startIndex = 0; startIndex = text.indexOf(startExpression); while (startIndex >= 0) { int endIndex = text.indexOf(endExpression, startIndex); int commentLength; if (endIndex == -1) { commentLength = text.length() - startIndex; } else { commentLength = endIndex - startIndex + endExpression.matchedLength(); } setFormat(startIndex, commentLength, tokenFormat); startIndex = text.indexOf(startExpression, startIndex + commentLength); } }
void Log (const char * s) { QString msg(QString::fromUtf8(s)); QRegExp rx; // ignore 'Init:' and 'Mod:' prefixes rx.setPattern(QLatin1String("^\\s*(Init:|Mod:)\\s*")); int pos = rx.indexIn(msg); if (pos != -1) { msg = msg.mid(rx.matchedLength()); } else { // ignore activation of commands rx.setPattern(QLatin1String("^\\s*(\\+App::|Create|CmdC:|CmdG:|Act:)\\s*")); pos = rx.indexIn(msg); if (pos == 0) return; } splash->showMessage(msg.replace(QLatin1String("\n"), QString()), alignment, textColor); QMutex mutex; mutex.lock(); QWaitCondition().wait(&mutex, 50); }
QString OmaSaunalahti::getSentMessages(QString htmlContent) { QTextStream out(stdout); QString retval = QString(); QString messageExpTxt = "<tr><td class=\"tdcontent1\">(.*)</td><td class=\"tdcontent1\">(.*)</td><td class=\"tdcontent1\">(.*)</td></tr>"; QRegExp messageExp = QRegExp(messageExpTxt); QRegExp exp = QRegExp("<table cellpadding=\"7\" cellspacing=\"1\"><tr><td class=\"tdtitleheader\" colspan=\"3\">(.*)</td></tr><tr><td class=\"tdtitle\">(.*)</td><td class=\"tdtitle\">(.*)</td><td class=\"tdtitle\">(.*)</td></tr>("+messageExpTxt+")*"); int pos = exp.indexIn(htmlContent,0); out << exp.cap(1) << endl; out << exp.cap(2) << endl; out << exp.cap(3) << endl; out << exp.cap(4) << endl; QString data = exp.cap(4); pos = 0; while ((pos = messageExp.indexIn(data,pos))!=-1) { out << messageExp.cap(1) << "\t" << messageExp.cap(2) << "\t" << messageExp.cap(3) << endl; retval += QString("%0;%1;%2\n").arg(messageExp.cap(1)).arg(messageExp.cap(2)).arg(messageExp.cap(3)); pos += messageExp.matchedLength(); } return retval; }
QList<QLyric> Lyrics::parse(QTextStream &stream) { QRegExp timeExp; timeExp.setPatternSyntax(QRegExp::RegExp); timeExp.setCaseSensitivity(Qt::CaseSensitive); timeExp.setPattern("\\[([0-9]{2}):([0-9]{2})\\.([0-9]{2})\\]"); QList<QLyric> result; while (!stream.atEnd()) { QString line = stream.readLine(); int ret = timeExp.indexIn(line); QList<QTime> ticks; int lastindex = 0; while (ret >= 0) { QStringList tstr = timeExp.capturedTexts(); QTime time(0, tstr[1].toInt(), tstr[2].toInt(), tstr[3].toInt()); ticks.append(time); lastindex = ret + timeExp.matchedLength(); ret = timeExp.indexIn(line, lastindex); } QString lyricstr = line.right(line.size() - lastindex); for (const QTime& t : ticks) { QLyric lyric; lyric.time = t.minute() * 60 * 1000 + t.second() * 1000 + t.msec(); lyric.lyric = lyricstr; // qDebug() << lyricstr; result.append(lyric); } } std::sort(result.begin(), result.end(), [] (const QLyric& a, const QLyric& b) -> bool { return a.time < b.time; }); return result; }
QString TextMessage::autoFormat(QString qsPlain) { QRegExp qr; qr.setMinimal(true); qr.setPatternSyntax(QRegExp::RegExp2); qr.setCaseSensitivity(Qt::CaseInsensitive); qr.setPattern(QLatin1String("[\\r\\n]+")); qsPlain.replace(qr, QLatin1String("<br />")); qr.setPattern(QLatin1String("\\*(\\w+)\\*")); qsPlain.replace(qr, QLatin1String("<b>\\1</b>")); qr.setPattern(QLatin1String("\"([^\"]+)\"")); qsPlain.replace(qr, QLatin1String("\"<i>\\1</i>\"")); qr.setPattern(QLatin1String("[a-z-]+://[^ <]*")); qr.setMinimal(false); int idx = 0; do { idx = qr.indexIn(qsPlain, idx); if (idx >= 0) { QString url = qr.capturedTexts().at(0); QUrl u(url); if (u.isValid()) { int len = qr.matchedLength(); QString replacement = QString::fromLatin1("<a href=\"%1\">%1</a>").arg(url); qsPlain.replace(idx, len, replacement); idx += replacement.length(); } else { idx++; } } } while (idx >= 0); return qsPlain; }
void VideoFindProxy::HandleSearchResults (const QString& contents) { QRegExp upt ("<div class=\"aname\" style='width:255px; overflow: hidden'><a href=\"video(.*)\\?noiphone\">(.*)</a></div>", Qt::CaseSensitive, QRegExp::RegExp2); upt.setMinimal (true); int pos = 0; while ((pos = upt.indexIn (contents, pos)) >= 0) { QStringList captured = upt.capturedTexts (); QUrl url = QUrl (QString ("http://vk.com/video%1") .arg (captured.at (1))); QString title = captured.at (2); title.remove ("<span class=\"match\">").remove ("</span>"); VideoResult vr = { url, title }; VideoResults_ << vr; pos += upt.matchedLength (); } if (VideoResults_.size ()) { SetError (QString ()); beginInsertRows (QModelIndex (), 0, VideoResults_.size () - 1); endInsertRows (); } else SetError (tr ("Nothing found for %1") .arg (R_.String_)); }