TEST(RegularExpressionTest, match) { Poco::RegularExpression re1("[0-9]+"); EXPECT_TRUE(re1.match("123")); EXPECT_FALSE(re1.match("abc")); EXPECT_TRUE(re1.match("abc123", 3)); }
TEST(RegularExpressionTest, matchPos) { Poco::RegularExpression re1("[0-9]+"); Poco::RegularExpression::Match pos; EXPECT_EQ(1, re1.match("123", 0, pos)); EXPECT_EQ(0, pos.offset); EXPECT_EQ(3, pos.length); EXPECT_EQ(1, re1.match("ab12de90cd12d", 0, pos)); EXPECT_EQ(2, pos.offset); EXPECT_EQ(2, pos.length); EXPECT_EQ(0, re1.match("abcd", 0, pos)); EXPECT_EQ(std::string::npos, pos.offset); Poco::RegularExpression re2("([0-9]+) ([0-9]+)"); Poco::RegularExpression::MatchVec posVec; EXPECT_EQ(3, re2.match("123 456", 0, posVec)); EXPECT_EQ(0, posVec[0].offset); EXPECT_EQ(7, posVec[0].length); EXPECT_EQ(0, posVec[1].offset); EXPECT_EQ(3, posVec[1].length); EXPECT_EQ(4, posVec[2].offset); EXPECT_EQ(3, posVec[2].length); }
TEST(RegularExpressionTest, options) { Poco::RegularExpression re1("ABC"); EXPECT_FALSE(re1.match("abc", 0)); Poco::RegularExpression re2("ABC", Poco::RegularExpression::RE_CASELESS); EXPECT_TRUE(re2.match("abc", 0)); }
void CPlayer::replace_token(QString &str, QString token, QString val) { QRegExp re1(QString("\\{%1\\}").arg(token)); str = str.replace(re1, val); QRegExp re2(QString("\\{%1\\?([^}]*)\\}").arg(token)); if(val.trimmed()!="") str = str.replace(re2, "\\1"); else str = str.replace(re2, ""); }
TEST(RegularExpressionTest, subst) { std::string s = "123"; Poco::RegularExpression re1("[0-9]+"); Poco::RegularExpression re2("([0-9]+) ([0-9]+)"); re1.subst(s, "ABC"); EXPECT_EQ("ABC", s); s = "123 456"; re2.subst(s, "$2 $1"); EXPECT_EQ("456 123", s); }
void CommandMgr::HandleKeres(CommandMessage& recvData) { CNick(recvData); if(recvData.Args.length() <= recvData.firstSpace+1) { sIRCSession.SendChatMessage(PRIVMSG, recvData.GetChannel(), "Nincs paraméter!"); return; } string kiiras = sVezerlo.urlencode(recvData.Args.substr(recvData.firstSpace+1)); m_Curl = curl_easy_init(); if(m_Curl) { string bufferdata; curl_easy_setopt(m_Curl, CURLOPT_URL, format("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=0&rsz=small&q=%s", kiiras.c_str()).c_str()); curl_easy_setopt(m_Curl, CURLOPT_WRITEFUNCTION, CommandMgr::writer); curl_easy_setopt(m_Curl, CURLOPT_WRITEDATA, &bufferdata); CURLcode result = curl_easy_perform(m_Curl); curl_easy_cleanup(m_Curl); if(result == CURLE_OK) { boost::regex re("(\\\"unescapedUrl\\\"):\\\"(?<url>\\S+)\\\",\\\"url\\\""); boost::cmatch matches; boost::regex_search(bufferdata.c_str(), matches, re); string matched(matches[2].first, matches[2].second); boost::regex re1(".titleNoFormatting.:.(.*).,.content.:."); boost::cmatch matches1; boost::regex_search(bufferdata.c_str(), matches1, re1); string matched1(matches1[1].first, matches1[1].second); int szokoz = matched1.find("\",\""); sIRCSession.SendChatMessage(PRIVMSG, recvData.GetChannel(), "2Title: %s", matched1.substr(0, szokoz).c_str()); sIRCSession.SendChatMessage(PRIVMSG, recvData.GetChannel(), "2Link: 9%s", matched.c_str()); } else { Log.Notice("IRCSession", "Keres: Hiba a Http lekerdezesben."); sIRCSession.SendChatMessage(PRIVMSG, recvData.GetChannel(), "Hibás találat"); } } else curl_easy_cleanup(m_Curl); }
void GlInfoView::draw(QPainter *p) { p->fillRect(geometry(), Qt::black); QLinearGradient gradient( getWidth()/2, getY(), getWidth()/2, getY() + getHeight()); gradient.setColorAt(0, gradientColorAt0); gradient.setColorAt(1, gradientColorAt1); p->setBrush(QBrush(gradient)); QPainterPath pa; QRect rect = geometry(); pa.addRoundedRect(rect, borderRadius, borderRadius); pen.setWidth(border); //Strichbreite pen.setColor(borderColor); //Strichfarbe p->setPen(pen); p->drawPath(pa); QFile testFile(mp.coverUrl); if(testFile.exists()) { coverImg.load(mp.coverUrl); coverImg = coverImg.scaled(200, 200); p->drawImage(getX() + 75, getY() + getHeight()/2 - 100, coverImg); } QFont font = p->font(); font.setPixelSize(fontSize); font.setBold(true); p->setFont(font); p->setPen(fontColor); QRect re(getX() + 300, getY() + getHeight()/2 + 10, 400, 30); p->drawText(re, mp.interpret); QRect re1(getX() + 300, getY() + getHeight()/2 + 40, 400, 30); p->drawText(re1, mp.album); QRect re2(getX() + 300, getY() + getHeight()/2 + 70, 400, 30); p->drawText(re2, mp.title); cbPoints->draw(p); }
TEST(RegularExpressionTest, extract) { std::string s; Poco::RegularExpression re1("[0-9]+"); Poco::RegularExpression re2("([0-9]+) ([0-9]+)"); EXPECT_EQ(1, re1.extract("123", s)); EXPECT_EQ("123", s); EXPECT_EQ(1, re1.extract("ab12de", 0, s)); EXPECT_EQ("12", s); EXPECT_EQ(0, re1.extract("abcd", 0, s)); EXPECT_EQ("", s); std::vector<std::string> vec; re2.split("123 456", 0, vec); // FIXME: split? EXPECT_EQ("123 456", vec[0]); EXPECT_EQ("123", vec[1]); EXPECT_EQ("456", vec[2]); }
/// Find the most appropriate configuration file for a given run /// @param run :: run number std::string EQSANSLoad::findConfigFile(const int& run) { // Append the standard location of EQSANS config file to the data search directory list std::string sns_folder = "/SNS/EQSANS/shared/instrument_configuration"; if (Poco::File(sns_folder).exists()) Kernel::ConfigService::Instance().appendDataSearchDir(sns_folder); const std::vector<std::string>& searchPaths = Kernel::ConfigService::Instance().getDataSearchDirs(); std::vector<std::string>::const_iterator it = searchPaths.begin(); int max_run_number = 0; std::string config_file = ""; Poco::RegularExpression re1("eqsans_configuration.[0-9]+"); Poco::RegularExpression re2("[0-9]+"); for (; it != searchPaths.end(); ++it) { Poco::DirectoryIterator file_it(*it); Poco::DirectoryIterator end; for (; file_it != end; ++file_it) { if (re1.match(file_it.name())) { std::string s; if (re2.extract(file_it.name(), s)==1) { int run_number = 0; Poco::NumberParser::tryParse(s, run_number); if (run_number > max_run_number && run_number <= run) { max_run_number = run_number; config_file = file_it.path().toString(); } } } } } return config_file; }
void PDB_Provider::setDir(const QString &_dir) { if(dir != _dir) { lb->clear(); // fill the listbox // set up filter dir = _dir; QString dir1 = KGlobal::dirs()->findDirs("appdata", "Provider").first(); QRegExp re1(" "); dir = dir.replace(re1, "_"); dir1 += dir; QDir d(dir1); d.setFilter(QDir::Files); d.setSorting(QDir::Name); // read the list of files const QFileInfoList *list = d.entryInfoList(); QFileInfoListIterator it( *list ); QFileInfo *fi; // traverse the list and insert into the widget QRegExp re("_"); while((fi = it.current()) != NULL) { QString fname = fi->fileName(); if(fname.length() && fname[0] != '.') { urlDecode(fname); lb->insertItem(fname); } ++it; } // TODO: Qt 1.x needs this if list is empty lb->update(); } }
void Thread::run() { while(stopped) { printMessage(); if(xinhao==0) { emit re(); } else if(xinhao==1) { emit re1(); } sleep(5); } }
QString niceType(QString type) { type.replace('*', '@'); for (int i = 0; i < 10; ++i) { int start = type.indexOf("std::allocator<"); if (start == -1) break; // search for matching '>' int pos; int level = 0; for (pos = start + 12; pos < type.size(); ++pos) { int c = type.at(pos).unicode(); if (c == '<') { ++level; } else if (c == '>') { --level; if (level == 0) break; } } QString alloc = type.mid(start, pos + 1 - start).trimmed(); QString inner = alloc.mid(15, alloc.size() - 16).trimmed(); //qDebug() << "MATCH: " << pos << alloc << inner; if (inner == QLatin1String("char")) // std::string type.replace(QLatin1String("basic_string<char, std::char_traits<char>, " "std::allocator<char> >"), QLatin1String("string")); else if (inner == QLatin1String("wchar_t")) // std::wstring type.replace(QLatin1String("basic_string<wchar_t, std::char_traits<wchar_t>, " "std::allocator<wchar_t> >"), QLatin1String("wstring")); // std::vector, std::deque, std::list QRegExp re1(QString("(vector|list|deque)<%1, %2\\s*>").arg(inner, alloc)); if (re1.indexIn(type) != -1) type.replace(re1.cap(0), QString("%1<%2>").arg(re1.cap(1), inner)); // std::stack QRegExp re6(QString("stack<%1, std::deque<%2> >").arg(inner, inner)); re6.setMinimal(true); if (re6.indexIn(type) != -1) type.replace(re6.cap(0), QString("stack<%1>").arg(inner)); // std::set QRegExp re4(QString("set<%1, std::less<%2>, %3\\s*>").arg(inner, inner, alloc)); re4.setMinimal(true); if (re4.indexIn(type) != -1) type.replace(re4.cap(0), QString("set<%1>").arg(inner)); // std::map if (inner.startsWith("std::pair<")) { // search for outermost ',' int pos; int level = 0; for (pos = 10; pos < inner.size(); ++pos) { int c = inner.at(pos).unicode(); if (c == '<') ++level; else if (c == '>') --level; else if (c == ',' && level == 0) break; } QString ckey = inner.mid(10, pos - 10); QString key = chopConst(ckey); QString value = inner.mid(pos + 2, inner.size() - 3 - pos); QRegExp re5(QString("map<%1, %2, std::less<%3>, %4\\s*>") .arg(key, value, key, alloc)); re5.setMinimal(true); if (re5.indexIn(type) != -1) type.replace(re5.cap(0), QString("map<%1, %2>").arg(key, value)); else { QRegExp re7(QString("map<const %1, %2, std::less<const %3>, %4\\s*>") .arg(key, value, key, alloc)); re7.setMinimal(true); if (re7.indexIn(type) != -1) type.replace(re7.cap(0), QString("map<const %1, %2>").arg(key, value)); } } } type.replace('@', '*'); type.replace(QLatin1String(" >"), QString(QLatin1Char('>'))); return type; }
static void parseClass(const QString& name, const QString& in) { Class cl; cl.name = name; QStringList sl = in.split("\n"); QStringList methodDescription; QRegExp re("@P ([^\\s]+)\\s+([^\\s]+)(.*)"); // matches Q_INVOKABLE void mops(int a); // comment QRegExp re1("Q_INVOKABLE +([^ ]+) +([^;]+); */*(.*)"); QRegExp re2("Q_INVOKABLE +([^ ]+) +([^\\{]+)\\{"); QRegExp re3("Q_INVOKABLE +([^ ]+) +(\\w+\\([^\\)]*\\))\\s+const\\s*([^\\{]*)\\{"); QRegExp reD("//@ (.*)"); QRegExp re4 ("class +(\\w+) *: *public +(\\w+) *\\{"); QRegExp re4b("class +(\\w+) *: *public +(\\w+), *public"); Q_ASSERT(re1.isValid() && re2.isValid() && re3.isValid()); bool parseClassDescription = true; foreach(const QString& s, sl) { if (re.indexIn(s, 0) != -1) { //@P parseClassDescription = false; Prop p; p.name = re.cap(1); p.type = re.cap(2); p.description = re.cap(3); cl.props.append(p); } else if (re2.indexIn(s, 0) != -1) { parseClassDescription = false; Proc p; p.type = re2.cap(1); p.name = re2.cap(2); p.description = methodDescription; methodDescription.clear(); cl.procs.append(p); } else if (re1.indexIn(s, 0) != -1) { parseClassDescription = false; Proc p; p.type = re1.cap(1); p.name = re1.cap(2); p.description = methodDescription; methodDescription.clear(); cl.procs.append(p); } else if (re3.indexIn(s, 0) != -1) { parseClassDescription = false; Proc p; p.type = re3.cap(1); p.name = re3.cap(2); p.description = methodDescription; methodDescription.clear(); cl.procs.append(p); } else if ((reD.indexIn(s, 0) != -1)) { if (parseClassDescription) cl.description.append(reD.cap(1)); else methodDescription.append(reD.cap(1)); } else if (s.startsWith("///")) { QString ss = s.mid(3); if (parseClassDescription) cl.description.append(ss); else methodDescription.append(ss); } else if (re4.indexIn(s, 0) != -1) { parseClassDescription = false; QString parent = re4.cap(2).simplified(); if (name == re4.cap(1).simplified()) { cl.parent = parent; } else { printf("?<%s>!=<%s> derived from <%s>\n", qPrintable(name), qPrintable(re4.cap(1).simplified()), qPrintable(parent)); } } else if (re4b.indexIn(s, 0) != -1) { parseClassDescription = false; QString parent = re4b.cap(2).simplified(); if (name == re4b.cap(1).simplified()) { cl.parent = parent; } else { printf("?<%s>!=<%s> derived from <%s>\n", qPrintable(name), qPrintable(re4b.cap(1).simplified()), qPrintable(parent)); } } } classes.append(cl); }
void QgsValueMapConfigDlg::loadFromCSVButtonPushed() { QString fileName = QFileDialog::getOpenFileName( 0, tr( "Select a file" ) ); if ( fileName.isNull() ) return; QFile f( fileName ); if ( !f.open( QIODevice::ReadOnly ) ) { QMessageBox::information( NULL, tr( "Error" ), tr( "Could not open file %1\nError was:%2" ).arg( fileName, f.errorString() ), QMessageBox::Cancel ); return; } QTextStream s( &f ); s.setAutoDetectUnicode( true ); QRegExp re0( "^([^;]*);(.*)$" ); re0.setMinimal( true ); QRegExp re1( "^([^,]*),(.*)$" ); re1.setMinimal( true ); QMap<QString, QVariant> map; s.readLine(); while ( !s.atEnd() ) { QString l = s.readLine().trimmed(); QString key, val; if ( re0.indexIn( l ) >= 0 && re0.captureCount() == 2 ) { key = re0.cap( 1 ).trimmed(); val = re0.cap( 2 ).trimmed(); } else if ( re1.indexIn( l ) >= 0 && re1.captureCount() == 2 ) { key = re1.cap( 1 ).trimmed(); val = re1.cap( 2 ).trimmed(); } else continue; if (( key.startsWith( "\"" ) && key.endsWith( "\"" ) ) || ( key.startsWith( "'" ) && key.endsWith( "'" ) ) ) { key = key.mid( 1, key.length() - 2 ); } if (( val.startsWith( "\"" ) && val.endsWith( "\"" ) ) || ( val.startsWith( "'" ) && val.endsWith( "'" ) ) ) { val = val.mid( 1, val.length() - 2 ); } map[ key ] = val; } updateMap( map, false ); }
//----------------------------------------------------------------- QString Utils::formatString(const QString filename, const Utils::FormatConfiguration &conf, bool add_mp3_extension) { // works for filenames and plain strings QString formattedName = filename; auto fileInfo = QFileInfo(filename); if(fileInfo.exists()) { formattedName = fileInfo.absoluteFilePath().split('/').last(); auto extension = formattedName.split('.').last(); auto extension_id = QString("*.") + extension; bool identified = WAVE_FILE_EXTENSIONS.contains(extension_id) || MODULE_FILE_EXTENSIONS.contains(extension_id) || MOVIE_FILE_EXTENSIONS.contains(extension_id); if (identified) { formattedName.remove(formattedName.lastIndexOf('.'), extension.length() + 1); } } if (conf.apply) { // delete specified chars for (int i = 0; i < conf.chars_to_delete.length(); ++i) { formattedName.remove(conf.chars_to_delete[i], Qt::CaseInsensitive); } // replace specified strings for (int i = 0; i < conf.chars_to_replace.size(); ++i) { auto charPair = conf.chars_to_replace[i]; formattedName.replace(charPair.first, charPair.second, Qt::CaseInsensitive); } // remove consecutive spaces QStringList parts = formattedName.split(' '); parts.removeAll(""); formattedName.clear(); int index = 0; // adjust the number prefix and insert the default separator. // Format 1: 01 ... QRegExp re1("\\d*"); auto re1_match = re1.exactMatch(parts[index]); // Format 2: 1-01 ... QRegExp re2("\\d-\\d*"); auto re2_match = re2.exactMatch(parts[index]); // only check number format if it exists if (re1_match || re2_match) { QString number_string, number_disc_id; if(re1_match) { number_string = parts[index]; } else { auto splits = parts[index].split('-'); number_disc_id = splits.first(); number_string = splits.last(); } while (conf.number_of_digits > number_string.length()) { number_string = "0" + number_string; } if (index != parts.size() - 1) { if(parts[index + 1] != QString(conf.number_and_name_separator)) { number_string += QString(' ' + conf.number_and_name_separator + ' '); } else { parts[index + 1] = QString(' ' + conf.number_and_name_separator); } } if(!number_disc_id.isEmpty() && conf.prefix_disk_num) { number_string = number_disc_id + QString("-") + number_string; } formattedName = number_string; ++index; } // capitalize the first letter of every word if (conf.to_title_case) { int i = index; while (i < parts.size()) { if (parts[i].isEmpty()) continue; bool starts_with_parenthesis = false; bool ends_with_parenthesis = false; bool starts_with_quote = false; bool ends_with_quote = false; int begin_quote_num = 0; int end_quote_num = 0; if(parts[i].startsWith('(') && parts[i].size() > 1) { starts_with_parenthesis = true; parts[i].remove('('); } if(parts[i].endsWith(')') && parts[i].size() > 1) { ends_with_parenthesis = true; parts[i].remove(')'); } if(parts[i].startsWith('\'') && parts[i].size() > 1) { starts_with_quote = true; while(parts[i].at(begin_quote_num) == QChar('\'') && begin_quote_num < parts[i].size()) { ++begin_quote_num; } } if(parts[i].endsWith('\'') && parts[i].size() > 1) { ends_with_quote = true; auto part_size = parts[i].size() - 1; while(parts[i].at(part_size - end_quote_num) == QChar('\'') && end_quote_num < parts[i].size()) { ++end_quote_num; } } if(starts_with_quote || ends_with_quote) { parts[i].remove(QChar('\'')); } if(!isRomanNumeral(parts[i])) { parts[i] = parts[i].toLower(); parts[i].replace(0, 1, parts[i].at(0).toUpper()); } if(starts_with_quote) { while(begin_quote_num > 0) { parts[i].insert(0, QChar('\'')); --begin_quote_num; } } if(ends_with_quote) { while(end_quote_num > 0) { parts[i].append(QChar('\'')); --end_quote_num; } } if (starts_with_parenthesis) { parts[i] = QString('(') + parts[i]; } if (ends_with_parenthesis) { parts[i] = parts[i] + QString(')'); } ++i; } } if(index < parts.size()) { formattedName += parts[index++]; } // compose the name. while (index < parts.size()) { formattedName += ' ' + parts[index++]; } } if(add_mp3_extension) { formattedName += ".mp3"; } // remove any unwanted spaces formattedName = formattedName.simplified(); // check for unwanted unicode chars while(formattedName.toLatin1().contains('?')) { auto index = formattedName.toLatin1().indexOf('?'); switch(formattedName.at(index).category()) { case QChar::Punctuation_InitialQuote: case QChar::Punctuation_FinalQuote: formattedName = formattedName.replace(formattedName.at(index), QString("''")); break; case QChar::Punctuation_Dash: formattedName = formattedName.replace(formattedName.at(index), '-'); break; default: formattedName = formattedName.replace(formattedName.at(index), ' '); } } return formattedName; }
Settings::Settings() { static_assert(TEAM_BLUE == blue && TEAM_RED == red && TEAM_YELLOW == yellow && TEAM_BLACK == black && TEAM_WHITE == white && TEAM_GREEN == green && TEAM_ORANGE == orange && TEAM_PURPLE == purple && TEAM_BROWN == brown && TEAM_GRAY == gray, "These macros and enums have to match!"); if(!loaded) { VERIFY(settings.load()); loaded = true; } *this = settings; #ifdef TARGET_SIM if(SystemCall::getMode() == SystemCall::simulatedRobot) { int index = atoi(RoboCupCtrl::controller->getRobotName().c_str() + 5) - 1; teamNumber = index < 6 ? 1 : 2; teamPort = 10000 + teamNumber; teamColor = index < 6 ? TeamColor(RoboCupCtrl::controller->gameController.teamInfos[0].teamColor) : TeamColor(RoboCupCtrl::controller->gameController.teamInfos[1].teamColor); playerNumber = index % 6 + 1; } headName = bodyName = "Nao"; ConsoleRoboCupCtrl* ctrl = dynamic_cast<ConsoleRoboCupCtrl*>(RoboCupCtrl::controller); if(ctrl) { std::string logFileName = ctrl->getLogFile(); if(logFileName != "") { QRegExp re1("([A-Za-z]*)_([A-Za-z]*)__", Qt::CaseSensitive, QRegExp::RegExp2); QRegExp re2("([A-Za-z]*)_([A-Za-z]*)_([A-Za-z0-9]*)_([A-Za-z0-9]*)__"); QRegExp re3("_([0-9][0-9]*)(_\\([0-9][0-9]*\\)){0,1}\\."); int pos1 = re1.indexIn(logFileName.c_str()); int pos2 = re2.indexIn(logFileName.c_str()); int pos3 = re3.indexIn(logFileName.c_str()); if(pos2 != -1) { headName = re2.capturedTexts()[1].toUtf8().constData(); bodyName = re2.capturedTexts()[2].toUtf8().constData(); scenario = re2.capturedTexts()[3].toUtf8().constData(); location = re2.capturedTexts()[4].toUtf8().constData(); } else if(pos1 != -1) { headName = re1.capturedTexts()[1].toUtf8().constData(); bodyName = re1.capturedTexts()[2].toUtf8().constData(); } else bodyName = headName = "Default"; if(pos3 != -1) playerNumber = re3.capturedTexts()[1].toUtf8().constData()[0] - '0'; } } #endif }
void regexp_pme() { static const char *underline = "----------------------------------------------------------------\n"; // Match tests { printf("Global matching\n%s", underline); TPMERegexp re("ba[rz]", "g"); TString m("foobarbaz"); while (re.Match(m)) re.Print("all"); printf("\n"); printf("Global matching with back-refs\n%s", underline); TPMERegexp re1("(ba[rz])", "g"); TString m1("foobarbaz"); while (re1.Match(m1)) re1.Print("all"); printf("\n"); printf("Matching with nested back-refs\n%s", underline); TPMERegexp re2("([\\w\\.-]+)@((\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+))"); TString m2("[email protected]"); re2.Match(m2); re2.Print("all"); printf("\n"); } // Split tests { printf("Split\n%s", underline); TPMERegexp re(":"); TString m("root:x:0:0:root:/root:/bin/bash"); re.Split(m); re.Print("all"); printf("\n"); printf("Split with maxfields=5\n%s", underline); re.Split(m, 5); re.Print("all"); printf("\n"); printf("Split with empty elements in the middle and at the end\n" "maxfields=0, so trailing empty elements are dropped\n%s", underline); m = "root::0:0:root:/root::"; re.Split(m); re.Print("all"); printf("\n"); printf("Split with empty elements at the beginning and end\n" "maxfields=-1, so trailing empty elements are kept\n%s", underline); m = ":x:0:0:root::"; re.Split(m, -1); re.Print("all"); printf("\n"); printf("Split with no pattern in string\n%s", underline); m = "A dummy line of text."; re.Split(m); re.Print("all"); printf("\n"); } { printf("Split with regexp potentially matching a null string \n%s", underline); TPMERegexp re(" *"); TString m("hi there"); re.Split(m); re.Print("all"); printf("\n"); } { printf("Split on patteren with back-refs\n%s", underline); TPMERegexp re("([,-])"); TString m("1-10,20"); re.Split(m); re.Print("all"); printf("\n"); } // Substitute tests { printf("Substitute\n%s", underline); TPMERegexp re("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)"); TString m("137.138.170.210"); TString r("$4.$3.$2.$1"); TString s(m); re.Substitute(s, r); re.Print(); printf("Substitute '%s','%s' => '%s'\n", m.Data(), r.Data(), s.Data()); printf("\n"); } { printf("Global substitute\n%s", underline); TPMERegexp re("(\\w+)\\.(\\w+)@[\\w\\.-]+", "g"); TString m("[email protected], [email protected], [email protected]"); TString r("\\u$1 \\U$2\\E"); TString s(m); re.Substitute(s, r); re.Print(); printf("Substitute '%s','%s' => '%s'\n", m.Data(), r.Data(), s.Data()); printf("\n"); } }
CPLUSPLUS_EXPORT QString simplifySTLType(const QString &typeIn) { QString type = typeIn; if (type.startsWith(QLatin1String("class "))) // MSVC prepends class,struct type.remove(0, 6); if (type.startsWith(QLatin1String("struct "))) type.remove(0, 7); type.replace(QLatin1Char('*'), QLatin1Char('@')); for (int i = 0; i < 10; ++i) { // std::ifstream QRegExp ifstreamRE(QLatin1String("std::basic_ifstream<char,\\s*std::char_traits<char>\\s*>")); ifstreamRE.setMinimal(true); QTC_ASSERT(ifstreamRE.isValid(), return typeIn); if (ifstreamRE.indexIn(type) != -1) type.replace(ifstreamRE.cap(0), QLatin1String("std::ifstream")); // Anything with a std::allocator int start = type.indexOf(QLatin1String("std::allocator<")); if (start == -1) break; // search for matching '>' int pos; int level = 0; for (pos = start + 12; pos < type.size(); ++pos) { int c = type.at(pos).unicode(); if (c == '<') { ++level; } else if (c == '>') { --level; if (level == 0) break; } } const QString alloc = fixNestedTemplates(type.mid(start, pos + 1 - start).trimmed()); const QString inner = fixNestedTemplates(alloc.mid(15, alloc.size() - 16).trimmed()); const QString allocEsc = QRegExp::escape(alloc); const QString innerEsc = QRegExp::escape(inner); if (inner == QLatin1String("char")) { // std::string simplifyStdString(QLatin1String("char"), QLatin1String("string"), &type); } else if (inner == QLatin1String("wchar_t")) { // std::wstring simplifyStdString(QLatin1String("wchar_t"), QLatin1String("wstring"), &type); } else if (inner == QLatin1String("unsigned short")) { // std::wstring/MSVC simplifyStdString(QLatin1String("unsigned short"), QLatin1String("wstring"), &type); } // std::vector, std::deque, std::list QRegExp re1(QString::fromLatin1("(vector|list|deque)<%1, ?%2\\s*>").arg(innerEsc, allocEsc)); QTC_ASSERT(re1.isValid(), return typeIn); if (re1.indexIn(type) != -1) type.replace(re1.cap(0), QString::fromLatin1("%1<%2>").arg(re1.cap(1), inner)); // std::stack QRegExp stackRE(QString::fromLatin1("stack<%1, ?std::deque<%2> >").arg(innerEsc, innerEsc)); stackRE.setMinimal(true); QTC_ASSERT(stackRE.isValid(), return typeIn); if (stackRE.indexIn(type) != -1) type.replace(stackRE.cap(0), QString::fromLatin1("stack<%1>").arg(inner)); // std::set QRegExp setRE(QString::fromLatin1("set<%1, ?std::less<%2>, ?%3\\s*>").arg(innerEsc, innerEsc, allocEsc)); setRE.setMinimal(true); QTC_ASSERT(setRE.isValid(), return typeIn); if (setRE.indexIn(type) != -1) type.replace(setRE.cap(0), QString::fromLatin1("set<%1>").arg(inner)); // std::map if (inner.startsWith(QLatin1String("std::pair<"))) { // search for outermost ',', split key and value int pos; int level = 0; for (pos = 10; pos < inner.size(); ++pos) { int c = inner.at(pos).unicode(); if (c == '<') ++level; else if (c == '>') --level; else if (c == ',' && level == 0) break; } const QString key = chopConst(inner.mid(10, pos - 10)); const QString keyEsc = QRegExp::escape(key); // Get value: MSVC: 'pair<a const ,b>', gcc: 'pair<const a, b>' if (inner.at(++pos) == QLatin1Char(' ')) pos++; const QString value = inner.mid(pos, inner.size() - pos - 1).trimmed(); const QString valueEsc = QRegExp::escape(value); QRegExp mapRE1(QString::fromLatin1("map<%1, ?%2, ?std::less<%3 ?>, ?%4\\s*>") .arg(keyEsc, valueEsc, keyEsc, allocEsc)); mapRE1.setMinimal(true); QTC_ASSERT(mapRE1.isValid(), return typeIn); if (mapRE1.indexIn(type) != -1) { type.replace(mapRE1.cap(0), QString::fromLatin1("map<%1, %2>").arg(key, value)); } else { QRegExp mapRE2(QString::fromLatin1("map<const %1, ?%2, ?std::less<const %3>, ?%4\\s*>") .arg(keyEsc, valueEsc, keyEsc, allocEsc)); mapRE2.setMinimal(true); if (mapRE2.indexIn(type) != -1) type.replace(mapRE2.cap(0), QString::fromLatin1("map<const %1, %2>").arg(key, value)); } } }