Replace QRegExp with QRegularExpression

Revise `static` keyword usage, static is added to frequently used
instances.
This commit is contained in:
Chocobo1 2018-05-24 23:41:03 +08:00
parent c22e6b4502
commit 09f759355f
No known key found for this signature in database
GPG key ID: 210D9C873253A68C
14 changed files with 72 additions and 63 deletions

View file

@ -41,7 +41,7 @@
#include <QDir>
#include <QFile>
#include <QRegExp>
#include <QRegularExpression>
#include <QString>
#ifndef DISABLE_GUI
@ -114,8 +114,9 @@ bool upgradeResumeFile(const QString &filepath, const QVariantHash &oldTorrent =
bool v3_3 = false;
int queuePosition = 0;
QString outFilePath = filepath;
QRegExp rx(QLatin1String("([A-Fa-f0-9]{40})\\.fastresume\\.(.+)$"));
if (rx.indexIn(filepath) != -1) {
static const QRegularExpression rx(QLatin1String("([A-Fa-f0-9]{40})\\.fastresume\\.(.+)$"));
const QRegularExpressionMatch rxMatch = rx.match(filepath);
if (rxMatch.hasMatch()) {
// Old v3.3.x format had a number at the end indicating the queue position.
// The naming scheme was '<infohash>.fastresume.<queueposition>'.
// However, QSaveFile, which uses QTemporaryFile internally, might leave
@ -127,14 +128,14 @@ bool upgradeResumeFile(const QString &filepath, const QVariantHash &oldTorrent =
// and is deleted, because it may be a corrupted/incomplete fastresume.
// NOTE: When the upgrade code is removed, we must continue to perform
// cleanup of non-commited QSaveFile/QTemporaryFile fastresumes
queuePosition = rx.cap(2).toInt();
if ((rx.cap(2).size() == 6) && (queuePosition <= 99999)) {
queuePosition = rxMatch.captured(2).toInt();
if ((rxMatch.captured(2).size() == 6) && (queuePosition <= 99999)) {
Utils::Fs::forceRemove(filepath);
return true;
}
v3_3 = true;
outFilePath.replace(QRegExp("\\.fastresume\\..+$"), ".fastresume");
outFilePath.replace(QRegularExpression("\\.fastresume\\..+$"), ".fastresume");
}
else {
queuePosition = fastOld.dict_find_int_value("qBt-queuePosition", 0);
@ -198,13 +199,15 @@ bool upgrade(bool ask = true)
QStringList backupFiles = backupFolderDir.entryList(
QStringList(QLatin1String("*.fastresume")), QDir::Files, QDir::Unsorted);
QRegExp rx(QLatin1String("^([A-Fa-f0-9]{40})\\.fastresume$"));
const QRegularExpression rx(QLatin1String("^([A-Fa-f0-9]{40})\\.fastresume$"));
foreach (QString backupFile, backupFiles) {
if (rx.indexIn(backupFile) != -1) {
if (upgradeResumeFile(backupFolderDir.absoluteFilePath(backupFile), oldResumeData[rx.cap(1)].toHash()))
oldResumeData.remove(rx.cap(1));
const QRegularExpressionMatch rxMatch = rx.match(backupFile);
if (rxMatch.hasMatch()) {
const QString hashStr = rxMatch.captured(1);
if (upgradeResumeFile(backupFolderDir.absoluteFilePath(backupFile), oldResumeData[hashStr].toHash()))
oldResumeData.remove(hashStr);
else
Logger::instance()->addMessage(QObject::tr("Couldn't migrate torrent with hash: %1").arg(rx.cap(1)), Log::WARNING);
Logger::instance()->addMessage(QObject::tr("Couldn't migrate torrent with hash: %1").arg(hashStr), Log::WARNING);
}
else {
Logger::instance()->addMessage(QObject::tr("Couldn't migrate torrent. Invalid fastresume file name: %1").arg(backupFile), Log::WARNING);

View file

@ -33,7 +33,7 @@
#include <libtorrent/magnet_uri.hpp>
#include <QByteArray>
#include <QRegExp>
#include <QRegularExpression>
#include <QStringList>
#include "base/utils/string.h"
@ -70,8 +70,8 @@ MagnetUri::MagnetUri(const QString &source)
qDebug("Creating magnet link from bc link");
m_url = bcLinkToMagnet(source);
}
else if (((source.size() == 40) && !source.contains(QRegExp("[^0-9A-Fa-f]")))
|| ((source.size() == 32) && !source.contains(QRegExp("[^2-7A-Za-z]")))) {
else if (((source.size() == 40) && !source.contains(QRegularExpression("[^0-9A-Fa-f]")))
|| ((source.size() == 32) && !source.contains(QRegularExpression("[^2-7A-Za-z]")))) {
m_url = "magnet:?xt=urn:btih:" + source;
}

View file

@ -42,7 +42,7 @@
#include <QNetworkAddressEntry>
#include <QNetworkInterface>
#include <QProcess>
#include <QRegExp>
#include <QRegularExpression>
#include <QString>
#include <QThread>
#include <QTimer>
@ -692,8 +692,8 @@ QString Session::torrentTempPath(const TorrentInfo &torrentInfo) const
bool Session::isValidCategoryName(const QString &name)
{
QRegExp re(R"(^([^\\\/]|[^\\\/]([^\\\/]|\/(?=[^\/]))*[^\\\/])$)");
if (!name.isEmpty() && (re.indexIn(name) != 0)) {
static const QRegularExpression re(R"(^([^\\\/]|[^\\\/]([^\\\/]|\/(?=[^\/]))*[^\\\/])$)");
if (!name.isEmpty() && (name.indexOf(re) != 0)) {
qDebug() << "Incorrect category name:" << name;
return false;
}
@ -3829,11 +3829,12 @@ void Session::startUpTorrents()
QMap<int, TorrentResumeData> queuedResumeData;
int nextQueuePosition = 1;
int numOfRemappedFiles = 0;
QRegExp rx(QLatin1String("^([A-Fa-f0-9]{40})\\.fastresume$"));
const QRegularExpression rx(QLatin1String("^([A-Fa-f0-9]{40})\\.fastresume$"));
foreach (const QString &fastresumeName, fastresumes) {
if (rx.indexIn(fastresumeName) == -1) continue;
const QRegularExpressionMatch rxMatch = rx.match(fastresumeName);
if (!rxMatch.hasMatch()) continue;
QString hash = rx.cap(1);
QString hash = rxMatch.captured(1);
QString fastresumePath = resumeDataDir.absoluteFilePath(fastresumeName);
QByteArray data;
AddTorrentData resumeData;

View file

@ -29,7 +29,7 @@
#include "dnsupdater.h"
#include <QDebug>
#include <QRegExp>
#include <QRegularExpression>
#include <QStringList>
#include <QUrlQuery>
@ -90,9 +90,9 @@ void DNSUpdater::ipRequestFinished(const QString &url, const QByteArray &data)
Q_UNUSED(url);
// Parse response
QRegExp ipregex("Current IP Address:\\s+([^<]+)</body>");
if (ipregex.indexIn(data) >= 0) {
QString ipStr = ipregex.cap(1);
const QRegularExpressionMatch ipRegexMatch = QRegularExpression("Current IP Address:\\s+([^<]+)</body>").match(data);
if (ipRegexMatch.hasMatch()) {
QString ipStr = ipRegexMatch.captured(1);
qDebug() << Q_FUNC_INFO << "Regular expression captured the following IP:" << ipStr;
QHostAddress newIp(ipStr);
if (!newIp.isNull()) {
@ -247,8 +247,8 @@ void DNSUpdater::updateCredentials()
}
if (m_domain != pref->getDynDomainName()) {
m_domain = pref->getDynDomainName();
QRegExp domain_regex("^(?:(?!\\d|-)[a-zA-Z0-9\\-]{1,63}\\.)+[a-zA-Z]{2,}$");
if (domain_regex.indexIn(m_domain) < 0) {
const QRegularExpressionMatch domainRegexMatch = QRegularExpression("^(?:(?!\\d|-)[a-zA-Z0-9\\-]{1,63}\\.)+[a-zA-Z]{2,}$").match(m_domain);
if (!domainRegexMatch.hasMatch()) {
logger->addMessage(tr("Dynamic DNS error: supplied domain name is invalid."), Log::CRITICAL);
m_lastIP.clear();
m_ipCheckTimer.stop();

View file

@ -45,6 +45,7 @@
#ifdef Q_OS_WIN
#include <shlobj.h>
#include <winreg.h>
#include <QRegularExpression>
#endif
#ifdef Q_OS_MAC
@ -1021,13 +1022,14 @@ bool Preferences::isMagnetLinkAssocSet()
QSettings settings("HKEY_CURRENT_USER\\Software\\Classes", QSettings::NativeFormat);
// Check magnet link assoc
QRegExp exe_reg("\"([^\"]+)\".*");
QString shell_command = Utils::Fs::toNativePath(settings.value("magnet/shell/open/command/Default", "").toString());
if (exe_reg.indexIn(shell_command) < 0)
const QString shellCommand = Utils::Fs::toNativePath(settings.value("magnet/shell/open/command/Default", "").toString());
const QRegularExpressionMatch exeRegMatch = QRegularExpression("\"([^\"]+)\".*").match(shellCommand);
if (!exeRegMatch.hasMatch())
return false;
QString assoc_exe = exe_reg.cap(1);
qDebug("exe: %s", qUtf8Printable(assoc_exe));
if (assoc_exe.compare(Utils::Fs::toNativePath(qApp->applicationFilePath()), Qt::CaseInsensitive) != 0)
const QString assocExe = exeRegMatch.captured(1);
if (assocExe.compare(Utils::Fs::toNativePath(qApp->applicationFilePath()), Qt::CaseInsensitive) != 0)
return false;
return true;

View file

@ -37,6 +37,7 @@
#include <QFile>
#include <QFileInfo>
#include <QStorageInfo>
#include <QRegularExpression>
#include <sys/stat.h>
#include <sys/types.h>
@ -218,7 +219,7 @@ bool Utils::Fs::sameFiles(const QString &path1, const QString &path2)
QString Utils::Fs::toValidFileSystemName(const QString &name, bool allowSeparators, const QString &pad)
{
QRegExp regex(allowSeparators ? "[:?\"*<>|]+" : "[\\\\/:?\"*<>|]+");
const QRegularExpression regex(allowSeparators ? "[:?\"*<>|]+" : "[\\\\/:?\"*<>|]+");
QString validName = name.trimmed();
validName.replace(regex, pad);
@ -231,7 +232,7 @@ bool Utils::Fs::isValidFileSystemName(const QString &name, bool allowSeparators)
{
if (name.isEmpty()) return false;
QRegExp regex(allowSeparators ? "[:?\"*<>|]" : "[\\\\/:?\"*<>|]");
const QRegularExpression regex(allowSeparators ? "[:?\"*<>|]" : "[\\\\/:?\"*<>|]");
return !name.contains(regex);
}

View file

@ -50,7 +50,6 @@
#include <QDir>
#include <QFileInfo>
#include <QProcess>
#include <QRegExp>
#include <QRegularExpression>
#include <QSysInfo>
#include <QUrl>
@ -529,7 +528,7 @@ bool Utils::Misc::isUrl(const QString &s)
QString Utils::Misc::parseHtmlLinks(const QString &rawText)
{
QString result = rawText;
static QRegExp reURL(
static const QRegularExpression reURL(
"(\\s|^)" // start with whitespace or beginning of line
"("
"(" // case 1 -- URL with scheme
@ -576,12 +575,11 @@ QString Utils::Misc::parseHtmlLinks(const QString &rawText)
")"
);
// Capture links
result.replace(reURL, "\\1<a href=\"\\2\">\\2</a>");
// Capture links without scheme
static QRegExp reNoScheme("<a\\s+href=\"(?!http(s?))([a-zA-Z0-9\\?%=&/_\\.-:#]+)\\s*\">");
static const QRegularExpression reNoScheme("<a\\s+href=\"(?!https?)([a-zA-Z0-9\\?%=&/_\\.-:#]+)\\s*\">");
result.replace(reNoScheme, "<a href=\"http://\\1\">");
// to preserve plain text formatting
@ -632,7 +630,7 @@ void Utils::Misc::openFolderSelect(const QString &absolutePath)
|| (output == "nautilus-folder-handler.desktop")) {
proc.start("nautilus", {"--version"});
proc.waitForFinished();
const QString nautilusVerStr = QString(proc.readLine()).remove(QRegExp("[^0-9.]"));
const QString nautilusVerStr = QString(proc.readLine()).remove(QRegularExpression("[^0-9.]"));
using NautilusVersion = Utils::Version<int, 3>;
if (NautilusVersion::tryParse(nautilusVerStr, {1, 0, 0}) > NautilusVersion {3, 28})
proc.startDetached("nautilus", {Utils::Fs::toNativePath(path)});

View file

@ -34,7 +34,7 @@
#include <QKeyEvent>
#include <QLabel>
#include <QListWidgetItem>
#include <QRegExp>
#include <QRegularExpression>
#include "guiiconprovider.h"
@ -95,10 +95,10 @@ void LogListWidget::appendLine(const QString &line, const Log::MsgType &type)
void LogListWidget::copySelection()
{
static QRegExp htmlTag("<[^>]+>");
static const QRegularExpression htmlTag("<[^>]+>");
QStringList strings;
foreach (QListWidgetItem* it, selectedItems())
strings << static_cast<QLabel*>(itemWidget(it))->text().replace(htmlTag, "");
strings << static_cast<QLabel*>(itemWidget(it))->text().remove(htmlTag);
QApplication::clipboard()->setText(strings.join("\n"));
}

View file

@ -41,6 +41,7 @@
#include <QMimeData>
#include <QProcess>
#include <QPushButton>
#include <QRegularExpression>
#include <QScrollBar>
#include <QShortcut>
#include <QSplitter>
@ -1599,8 +1600,8 @@ void MainWindow::downloadFromURLList(const QStringList &urlList)
{
const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled();
foreach (QString url, urlList) {
if (((url.size() == 40) && !url.contains(QRegExp("[^0-9A-Fa-f]")))
|| ((url.size() == 32) && !url.contains(QRegExp("[^2-7A-Za-z]"))))
if (((url.size() == 40) && !url.contains(QRegularExpression("[^0-9A-Fa-f]")))
|| ((url.size() == 32) && !url.contains(QRegularExpression("[^2-7A-Za-z]"))))
url = "magnet:?xt=urn:btih:" + url;
if (useTorrentAdditionDialog)

View file

@ -30,7 +30,7 @@
#include <QDebug>
#include <QDesktopServices>
#include <QRegExp>
#include <QRegularExpression>
#include <QStringList>
#include <QXmlStreamReader>
@ -136,9 +136,9 @@ void ProgramUpdater::updateProgram()
bool ProgramUpdater::isVersionMoreRecent(const QString &remoteVersion) const
{
QRegExp regVer("([0-9.]+)");
if (regVer.indexIn(QBT_VERSION) >= 0) {
QString localVersion = regVer.cap(1);
const QRegularExpressionMatch regVerMatch = QRegularExpression("([0-9.]+)").match(QBT_VERSION);
if (regVerMatch.hasMatch()) {
QString localVersion = regVerMatch.captured(1);
qDebug() << Q_FUNC_INFO << "local version:" << localVersion << "/" << QBT_VERSION;
QStringList remoteParts = remoteVersion.split('.');
QStringList localParts = localVersion.split('.');
@ -152,8 +152,8 @@ bool ProgramUpdater::isVersionMoreRecent(const QString &remoteVersion) const
if (remoteParts.size() > localParts.size())
return true;
// versions are equal, check if the local version is a development release, in which case it is older (2.9.2beta < 2.9.2)
QRegExp regDevel("(alpha|beta|rc)");
if (regDevel.indexIn(QBT_VERSION) >= 0)
const QRegularExpressionMatch regDevelMatch = QRegularExpression("(alpha|beta|rc)").match(QBT_VERSION);
if (regDevelMatch.hasMatch())
return true;
}
return false;

View file

@ -36,6 +36,7 @@
#include <QDragMoveEvent>
#include <QMenu>
#include <QMessageBox>
#include <QRegularExpression>
#include <QStandardItemModel>
#include <QString>
@ -461,10 +462,10 @@ void RSSWidget::handleCurrentArticleItemChanged(QListWidgetItem *currentItem, QL
}
else {
QString description = article->description();
QRegExp rx;
QRegularExpression rx;
// If description is plain text, replace BBCode tags with HTML and wrap everything in <pre></pre> so it looks nice
rx.setMinimal(true);
rx.setCaseSensitivity(Qt::CaseInsensitive);
rx.setPatternOptions(QRegularExpression::InvertedGreedinessOption
| QRegularExpression::CaseInsensitiveOption);
rx.setPattern("\\[img\\](.+)\\[/img\\]");
description = description.replace(rx, "<img src=\"\\1\">");

View file

@ -43,7 +43,7 @@
#include <QMessageBox>
#include <QMimeData>
#include <QProcess>
#include <QRegExp>
#include <QRegularExpression>
#include <QSignalMapper>
#include <QSortFilterProxyModel>
#include <QStandardItemModel>
@ -323,7 +323,7 @@ void SearchWidget::on_searchButton_clicked()
m_allTabs.append(newTab);
QString tabName = pattern;
tabName.replace(QRegExp("&{1}"), "&&");
tabName.replace(QRegularExpression("&{1}"), "&&");
m_ui->tabWidget->addTab(newTab, tabName);
m_ui->tabWidget->setCurrentWidget(newTab);

View file

@ -34,6 +34,7 @@
#include <QMenu>
#include <QMessageBox>
#include <QRegExp>
#include <QRegularExpression>
#include <QShortcut>
#include <QStylePainter>
#include <QTableView>
@ -830,7 +831,7 @@ void TransferListWidget::renameSelectedTorrent()
bool ok;
QString name = AutoExpandableDialog::getText(this, tr("Rename"), tr("New name:"), QLineEdit::Normal, torrent->name(), &ok);
if (ok && !name.isEmpty()) {
name.replace(QRegExp("\r?\n|\r"), " ");
name.replace(QRegularExpression("\r?\n|\r"), " ");
// Rename the torrent
m_listModel->setData(mi, name, Qt::DisplayRole);
}

View file

@ -97,8 +97,8 @@ namespace
void translateDocument(const QString &locale, QString &data)
{
const QRegExp regex("QBT_TR\\((([^\\)]|\\)(?!QBT_TR))+)\\)QBT_TR(\\[CONTEXT=([a-zA-Z_][a-zA-Z0-9_]*)\\])");
const QRegExp mnemonic("\\(?&([a-zA-Z]?\\))?");
const QRegularExpression regex("QBT_TR\\((([^\\)]|\\)(?!QBT_TR))+)\\)QBT_TR(\\[CONTEXT=([a-zA-Z_][a-zA-Z0-9_]*)\\])");
const QRegularExpression mnemonic("\\(?&([a-zA-Z]?\\))?");
const bool isTranslationNeeded = !locale.startsWith("en")
|| locale.startsWith("en_AU") || locale.startsWith("en_GB");
@ -106,23 +106,24 @@ namespace
int i = 0;
bool found = true;
while (i < data.size() && found) {
i = regex.indexIn(data, i);
QRegularExpressionMatch regexMatch;
i = data.indexOf(regex, i, &regexMatch);
if (i >= 0) {
const QString word = regex.cap(1);
const QString context = regex.cap(4);
const QString word = regexMatch.captured(1);
const QString context = regexMatch.captured(4);
QString translation = isTranslationNeeded
? qApp->translate(context.toUtf8().constData(), word.toUtf8().constData(), nullptr, 1)
: word;
// Remove keyboard shortcuts
translation.replace(mnemonic, "");
translation.remove(mnemonic);
// Use HTML code for quotes to prevent issues with JS
translation.replace('\'', "&#39;");
translation.replace('\"', "&#34;");
data.replace(i, regex.matchedLength(), translation);
data.replace(i, regexMatch.capturedLength(), translation);
i += translation.length();
}
else {