C++ (Qt)QString str = "http://server.com/$user/docs/$version";
C++ (Qt)#include <QCoreApplication>#include <QDebug>#include <QMap> #include "qregexreplace.h" class Substitute{public: Substitute() { m_map["$user"] = "terminator"; m_map["$version"] = "T1000"; } QString operator()(const QString & match) const { auto it = m_map.find(match); if (it != m_map.end()) return it.value(); return match; } private: QMap<QString, QString> m_map;}; int main(){ QString str = "http://server.com/$user/docs/$version"; QRegularExpression rx("(\\$\\w+)"); qDebug() << qRegexReplace(str, rx, Substitute()); return 0;}
C++ (Qt)#ifndef QREGEXREPLACE_H#define QREGEXREPLACE_H #include <QRegularExpression>#include <QStringList>#include <QStringRef>#include <QList>#include <QPair> template <class FormatFunction>QString qRegexReplace(const QString & input, const QRegularExpression & regex, FormatFunction formatFunc){ int pos = 0; QString out; auto regexIt = regex.globalMatch(input); while (regexIt.hasNext()) { QRegularExpressionMatch match = regexIt.next(); QPair<int, int> r = qMakePair(match.capturedStart(1), match.capturedEnd(1)); out.append(QStringRef(&input, pos, r.first-pos)); out.append(formatFunc(match.captured(1))); pos = r.second; } out.append(QStringRef(&input, pos, input.size()-pos)); return out;} #endif // QREGEXREPLACE_H
C++ (Qt)QString out; out.reserve(input.size() - replacedTextLength + replacementTextLength);
C++ (Qt) out.append(QStringRef(&input, pos, r.first-pos)); out.append(*it++);
C++ (Qt)template <class FormatFunction>QString qRegexReplace(const QString & input, const QRegularExpression & regex, FormatFunction formatFunc){ int pos = 0; QString out; auto regexIt = regex.globalMatch(input); while (regexIt.hasNext()) { QRegularExpressionMatch match = regexIt.next(); QPair<int, int> r = qMakePair(match.capturedStart(1), match.capturedEnd(1)); out.append(QStringRef(&input, pos, r.first-pos)); out.append(formatFunc(match.captured(1))); pos = r.second; } out.append(QStringRef(&input, pos, input.size()-pos)); return out;}
C++ (Qt)int qAllocMore(int alloc, int extra) Q_DECL_NOTHROW{ Q_ASSERT(alloc >= 0 && extra >= 0); Q_ASSERT_X(alloc <= MaxAllocSize - extra, "qAllocMore", "Requested size is too large!"); unsigned nalloc = qNextPowerOfTwo(alloc + extra); Q_ASSERT(nalloc > unsigned(alloc + extra)); return nalloc - extra;}