use static (And const where applicable) regular expression objects

the speed increase here is noticable since the work of creating a regex object is only done once per session
This commit is contained in:
garak 2022-11-22 22:57:26 -05:00
parent cb8482c551
commit 86c7238a8a
18 changed files with 79 additions and 56 deletions

View file

@ -92,7 +92,7 @@ void KeyValueConfigBase::load() {
QTextStream in(&file); QTextStream in(&file);
QList<QString> configLines; QList<QString> configLines;
QRegularExpression re("^(?<key>[^=]+)=(?<value>.*)$"); static const QRegularExpression re("^(?<key>[^=]+)=(?<value>.*)$");
while (!in.atEnd()) { while (!in.atEnd()) {
QString line = in.readLine().trimmed(); QString line = in.readLine().trimmed();
int commentIndex = line.indexOf("#"); int commentIndex = line.indexOf("#");
@ -1132,7 +1132,7 @@ QString ShortcutsConfig::cfgKey(const QObject *object) const {
cfg_key = parentWidget->window()->objectName() + '_'; cfg_key = parentWidget->window()->objectName() + '_';
cfg_key += object->objectName(); cfg_key += object->objectName();
QRegularExpression re("[A-Z]"); static const QRegularExpression re("[A-Z]");
int i = cfg_key.indexOf(re, 1); int i = cfg_key.indexOf(re, 1);
while (i != -1) { while (i != -1) {
if (cfg_key.at(i - 1) != '_') if (cfg_key.at(i - 1) != '_')

View file

@ -31,9 +31,11 @@ void Map::setName(QString mapName) {
QString Map::mapConstantFromName(QString mapName) { QString Map::mapConstantFromName(QString mapName) {
// Transform map names of the form 'GraniteCave_B1F` into map constants like 'MAP_GRANITE_CAVE_B1F'. // Transform map names of the form 'GraniteCave_B1F` into map constants like 'MAP_GRANITE_CAVE_B1F'.
QString nameWithUnderscores = mapName.replace(QRegularExpression("([a-z])([A-Z])"), "\\1_\\2"); static const QRegularExpression caseChange("([a-z])([A-Z])");
QString nameWithUnderscores = mapName.replace(caseChange, "\\1_\\2");
QString withMapAndUppercase = "MAP_" + nameWithUnderscores.toUpper(); QString withMapAndUppercase = "MAP_" + nameWithUnderscores.toUpper();
QString constantName = withMapAndUppercase.replace(QRegularExpression("_+"), "_"); static const QRegularExpression underscores("_+");
QString constantName = withMapAndUppercase.replace(underscores, "_");
// Handle special cases. // Handle special cases.
// SSTidal needs to be SS_TIDAL, rather than SSTIDAL // SSTidal needs to be SS_TIDAL, rather than SSTIDAL

View file

@ -4,9 +4,11 @@
QString MapLayout::layoutConstantFromName(QString mapName) { QString MapLayout::layoutConstantFromName(QString mapName) {
// Transform map names of the form 'GraniteCave_B1F` into layout constants like 'LAYOUT_GRANITE_CAVE_B1F'. // Transform map names of the form 'GraniteCave_B1F` into layout constants like 'LAYOUT_GRANITE_CAVE_B1F'.
QString nameWithUnderscores = mapName.replace(QRegularExpression("([a-z])([A-Z])"), "\\1_\\2"); static const QRegularExpression caseChange("([a-z])([A-Z])");
QString nameWithUnderscores = mapName.replace(caseChange, "\\1_\\2");
QString withMapAndUppercase = "LAYOUT_" + nameWithUnderscores.toUpper(); QString withMapAndUppercase = "LAYOUT_" + nameWithUnderscores.toUpper();
QString constantName = withMapAndUppercase.replace(QRegularExpression("_+"), "_"); static const QRegularExpression underscores("_+");
QString constantName = withMapAndUppercase.replace(underscores, "_");
// Handle special cases. // Handle special cases.
// SSTidal should be SS_TIDAL, rather than SSTIDAL // SSTidal should be SS_TIDAL, rather than SSTIDAL

View file

@ -118,7 +118,7 @@ QList<QRgb> parseJASC(QString filepath, bool *error) {
} }
QList<QRgb> palette; QList<QRgb> palette;
QRegularExpression re("(?<red>\\d+)\\s(?<green>\\d+)\\s(?<blue>\\d+)"); static const QRegularExpression re("(?<red>\\d+)\\s(?<green>\\d+)\\s(?<blue>\\d+)");
while (!in.atEnd() && numColors > 0) { while (!in.atEnd() && numColors > 0) {
numColors--; numColors--;
QString line = in.readLine(); QString line = in.readLine();

View file

@ -40,7 +40,8 @@ void ParseUtil::logRecordedErrors() {
} }
QString ParseUtil::createErrorMessage(const QString &message, const QString &expression) { QString ParseUtil::createErrorMessage(const QString &message, const QString &expression) {
QStringList lines = this->text.split(QRegularExpression("[\r\n]")); static const QRegularExpression newline("[\r\n]");
QStringList lines = this->text.split(newline);
int lineNum = 0, colNum = 0; int lineNum = 0, colNum = 0;
for (QString line : lines) { for (QString line : lines) {
lineNum++; lineNum++;
@ -90,9 +91,11 @@ QList<QStringList> ParseUtil::parseAsm(const QString &filename) {
// There should not be anything else on the line. // There should not be anything else on the line.
// gas will raise a syntax error if there is. // gas will raise a syntax error if there is.
} else { } else {
int index = trimmedLine.indexOf(QRegularExpression("\\s+")); static const QRegularExpression re_spaces("\\s+");
int index = trimmedLine.indexOf(re_spaces);
const QString macro = trimmedLine.left(index); const QString macro = trimmedLine.left(index);
QStringList params(trimmedLine.right(trimmedLine.length() - index).trimmed().split(QRegularExpression("\\s*,\\s*"))); static const QRegularExpression re_spacesCommaSpaces("\\s*,\\s*");
QStringList params(trimmedLine.right(trimmedLine.length() - index).trimmed().split(re_spacesCommaSpaces));
params.prepend(macro); params.prepend(macro);
parsed.append(params); parsed.append(params);
} }
@ -110,7 +113,7 @@ QList<Token> ParseUtil::tokenizeExpression(QString expression, const QMap<QStrin
QList<Token> tokens; QList<Token> tokens;
QStringList tokenTypes = (QStringList() << "hex" << "decimal" << "identifier" << "operator" << "leftparen" << "rightparen"); QStringList tokenTypes = (QStringList() << "hex" << "decimal" << "identifier" << "operator" << "leftparen" << "rightparen");
QRegularExpression re("^(?<hex>0x[0-9a-fA-F]+)|(?<decimal>[0-9]+)|(?<identifier>[a-zA-Z_0-9]+)|(?<operator>[+\\-*\\/<>|^%]+)|(?<leftparen>\\()|(?<rightparen>\\))"); static const QRegularExpression re("^(?<hex>0x[0-9a-fA-F]+)|(?<decimal>[0-9]+)|(?<identifier>[a-zA-Z_0-9]+)|(?<operator>[+\\-*\\/<>|^%]+)|(?<leftparen>\\()|(?<rightparen>\\))");
expression = expression.trimmed(); expression = expression.trimmed();
while (!expression.isEmpty()) { while (!expression.isEmpty()) {
@ -257,7 +260,7 @@ QString ParseUtil::readCIncbin(const QString &filename, const QString &label) {
this->text = readTextFile(this->root + "/" + filename); this->text = readTextFile(this->root + "/" + filename);
QRegularExpression re(QString( static const QRegularExpression re(QString(
"\\b%1\\b" "\\b%1\\b"
"\\s*\\[?\\s*\\]?\\s*=\\s*" "\\s*\\[?\\s*\\]?\\s*=\\s*"
"INCBIN_[US][0-9][0-9]?" "INCBIN_[US][0-9][0-9]?"
@ -282,14 +285,14 @@ QStringList ParseUtil::readCIncbinArray(const QString &filename, const QString &
this->text = readTextFile(this->root + "/" + filename); this->text = readTextFile(this->root + "/" + filename);
// Get the text starting after the label all the way to the definition's end // Get the text starting after the label all the way to the definition's end
QRegularExpression re(QString("\\b%1\\b(.*?)};").arg(label), QRegularExpression::DotMatchesEverythingOption); static const QRegularExpression re_labelGroup(QString("\\b%1\\b(.*?)};").arg(label), QRegularExpression::DotMatchesEverythingOption);
QRegularExpressionMatch arrayMatch = re.match(this->text); QRegularExpressionMatch arrayMatch = re_labelGroup.match(this->text);
if (!arrayMatch.hasMatch()) if (!arrayMatch.hasMatch())
return paths; return paths;
// Extract incbin paths from the array // Extract incbin paths from the array
re.setPattern("INCBIN_[US][0-9][0-9]?\\(\\s*\"([^\"]*)\"\\s*\\)"); static const QRegularExpression re_incbin("INCBIN_[US][0-9][0-9]?\\(\\s*\"([^\"]*)\"\\s*\\)");
QRegularExpressionMatchIterator iter = re.globalMatch(arrayMatch.captured(1)); QRegularExpressionMatchIterator iter = re_incbin.globalMatch(arrayMatch.captured(1));
while (iter.hasNext()) { while (iter.hasNext()) {
paths.append(iter.next().captured(1)); paths.append(iter.next().captured(1));
} }
@ -316,12 +319,14 @@ QMap<QString, int> ParseUtil::readCDefines(const QString &filename,
return filteredDefines; return filteredDefines;
} }
this->text.replace(QRegularExpression("(//.*)|(\\/+\\*+[^*]*\\*+\\/+)"), ""); static const QRegularExpression re_extraChars("(//.*)|(\\/+\\*+[^*]*\\*+\\/+)");
this->text.replace(QRegularExpression("(\\\\\\s+)"), ""); this->text.replace(re_extraChars, "");
static const QRegularExpression re_extraSpaces("(\\\\\\s+)");
this->text.replace(re_extraSpaces, "");
allDefines.insert("FALSE", 0); allDefines.insert("FALSE", 0);
allDefines.insert("TRUE", 1); allDefines.insert("TRUE", 1);
QRegularExpression re("#define\\s+(?<defineName>\\w+)[^\\S\\n]+(?<defineValue>.+)"); static const QRegularExpression re("#define\\s+(?<defineName>\\w+)[^\\S\\n]+(?<defineValue>.+)");
QRegularExpressionMatchIterator iter = re.globalMatch(this->text); QRegularExpressionMatchIterator iter = re.globalMatch(this->text);
this->errorMap.clear(); this->errorMap.clear();
while (iter.hasNext()) { while (iter.hasNext()) {
@ -368,7 +373,7 @@ QStringList ParseUtil::readCArray(const QString &filename, const QString &label)
this->file = filename; this->file = filename;
this->text = readTextFile(this->root + "/" + filename); this->text = readTextFile(this->root + "/" + filename);
QRegularExpression re(QString(R"(\b%1\b\s*(\[?[^\]]*\])?\s*=\s*\{([^\}]*)\})").arg(label)); static const QRegularExpression re(QString(R"(\b%1\b\s*(\[?[^\]]*\])?\s*=\s*\{([^\}]*)\})").arg(label));
QRegularExpressionMatch match = re.match(this->text); QRegularExpressionMatch match = re.match(this->text);
if (match.hasMatch()) { if (match.hasMatch()) {
@ -376,7 +381,8 @@ QStringList ParseUtil::readCArray(const QString &filename, const QString &label)
QStringList split = body.split(','); QStringList split = body.split(',');
for (QString item : split) { for (QString item : split) {
item = item.trimmed(); item = item.trimmed();
if (!item.contains(QRegularExpression("[^A-Za-z0-9_&()\\s]"))) list.append(item); static const QRegularExpression validChars("[^A-Za-z0-9_&()\\s]");
if (!item.contains(validChars)) list.append(item);
// do not print error info here because this is called dozens of times // do not print error info here because this is called dozens of times
} }
} }
@ -388,10 +394,11 @@ QMap<QString, QString> ParseUtil::readNamedIndexCArray(const QString &filename,
this->text = readTextFile(this->root + "/" + filename); this->text = readTextFile(this->root + "/" + filename);
QMap<QString, QString> map; QMap<QString, QString> map;
QRegularExpression re_text(QString(R"(\b%1\b\s*(\[?[^\]]*\])?\s*=\s*\{([^\}]*)\})").arg(label)); static const QRegularExpression re_text(QString(R"(\b%1\b\s*(\[?[^\]]*\])?\s*=\s*\{([^\}]*)\})").arg(label));
QString body = re_text.match(this->text).captured(2).replace(QRegularExpression("\\s*"), ""); static const QRegularExpression re_spaces("\\s*");
QString body = re_text.match(this->text).captured(2).replace(re_spaces, "");
QRegularExpression re("\\[(?<index>[A-Za-z0-9_]*)\\]=(?<value>&?[A-Za-z0-9_]*)"); static const QRegularExpression re("\\[(?<index>[A-Za-z0-9_]*)\\]=(?<value>&?[A-Za-z0-9_]*)");
QRegularExpressionMatchIterator iter = re.globalMatch(body); QRegularExpressionMatchIterator iter = re.globalMatch(body);
while (iter.hasNext()) { while (iter.hasNext()) {

View file

@ -161,7 +161,7 @@ bool RegionMap::loadLayout(poryjson::Json layoutJson) {
ParseUtil parser; ParseUtil parser;
QString text = parser.readTextFile(fullPath(this->layout_path)); QString text = parser.readTextFile(fullPath(this->layout_path));
QRegularExpression re("(?<qual_1>static)?\\s?(?<qual_2>const)?\\s?(?<type>[A-Za-z0-9_]+)?\\s+(?<label>[A-Za-z0-9_]+)" static const QRegularExpression re("(?<qual_1>static)?\\s?(?<qual_2>const)?\\s?(?<type>[A-Za-z0-9_]+)?\\s+(?<label>[A-Za-z0-9_]+)"
"(\\[(?<const_1>[A-Za-z0-9_]+)\\])(\\[(?<const_2>[A-Za-z0-9_]+)\\])(\\[(?<const_3>[A-Za-z0-9_]+)\\])\\s+="); "(\\[(?<const_1>[A-Za-z0-9_]+)\\])(\\[(?<const_2>[A-Za-z0-9_]+)\\])(\\[(?<const_3>[A-Za-z0-9_]+)\\])\\s+=");
// check for layers, extract info // check for layers, extract info
@ -179,7 +179,7 @@ bool RegionMap::loadLayout(poryjson::Json layoutJson) {
this->layout_array_label = label; this->layout_array_label = label;
// find layers // find layers
QRegularExpression reLayers("(?<layer>\\[(?<label>LAYER_[A-Za-z0-9_]+)\\][^\\[\\]]+)"); static const QRegularExpression reLayers("(?<layer>\\[(?<label>LAYER_[A-Za-z0-9_]+)\\][^\\[\\]]+)");
QRegularExpressionMatchIterator i = reLayers.globalMatch(text); QRegularExpressionMatchIterator i = reLayers.globalMatch(text);
while (i.hasNext()) { while (i.hasNext()) {
QRegularExpressionMatch m = i.next(); QRegularExpressionMatch m = i.next();
@ -187,7 +187,7 @@ bool RegionMap::loadLayout(poryjson::Json layoutJson) {
QString layerName = m.captured("label"); QString layerName = m.captured("label");
QString layerLayout = m.captured("layer"); QString layerLayout = m.captured("layer");
QRegularExpression rowRe("{(?<row>[A-Z0-9_, ]+)}"); static const QRegularExpression rowRe("{(?<row>[A-Z0-9_, ]+)}");
QRegularExpressionMatchIterator j = rowRe.globalMatch(layerLayout); QRegularExpressionMatchIterator j = rowRe.globalMatch(layerLayout);
this->layout_layers.append(layerName); this->layout_layers.append(layerName);
@ -217,7 +217,7 @@ bool RegionMap::loadLayout(poryjson::Json layoutJson) {
} else { } else {
// try single-layered // try single-layered
QRegularExpression reAlt("(?<qual_1>static)?\\s?(?<qual_2>const)?\\s?(?<type>[A-Za-z0-9_]+)?\\s+(?<label>[A-Za-z0-9_]+)\\[\\]"); static const QRegularExpression reAlt("(?<qual_1>static)?\\s?(?<qual_2>const)?\\s?(?<type>[A-Za-z0-9_]+)?\\s+(?<label>[A-Za-z0-9_]+)\\[\\]");
QRegularExpressionMatch matchAlt = reAlt.match(text); QRegularExpressionMatch matchAlt = reAlt.match(text);
if (matchAlt.hasMatch()) { if (matchAlt.hasMatch()) {
// single dimensional // single dimensional
@ -228,7 +228,7 @@ bool RegionMap::loadLayout(poryjson::Json layoutJson) {
this->layout_qualifiers = qualifiers + " " + type; this->layout_qualifiers = qualifiers + " " + type;
this->layout_array_label = label; this->layout_array_label = label;
QRegularExpression reSec("(?<sec>MAPSEC_[A-Za-z0-9_]+)"); static const QRegularExpression reSec("(?<sec>MAPSEC_[A-Za-z0-9_]+)");
QRegularExpressionMatchIterator k = reSec.globalMatch(text); QRegularExpressionMatchIterator k = reSec.globalMatch(text);
QList<LayoutSquare> layout; QList<LayoutSquare> layout;
@ -252,7 +252,7 @@ bool RegionMap::loadLayout(poryjson::Json layoutJson) {
this->layout_layers.append("main"); this->layout_layers.append("main");
setLayout("main", layout); setLayout("main", layout);
} else { } else {
QRegularExpression reAlt2("(?<qual_1>static)?\\s?(?<qual_2>const)?\\s?(?<type>[A-Za-z0-9_]+)?\\s+(?<label>[A-Za-z0-9_]+)" static const QRegularExpression reAlt2("(?<qual_1>static)?\\s?(?<qual_2>const)?\\s?(?<type>[A-Za-z0-9_]+)?\\s+(?<label>[A-Za-z0-9_]+)"
"(\\[(?<const_1>[A-Za-z0-9_]+)\\])(\\[(?<const_2>[A-Za-z0-9_]+)\\])\\s+="); "(\\[(?<const_1>[A-Za-z0-9_]+)\\])(\\[(?<const_2>[A-Za-z0-9_]+)\\])\\s+=");
QRegularExpressionMatch matchAlt2 = reAlt2.match(text); QRegularExpressionMatch matchAlt2 = reAlt2.match(text);
if (matchAlt2.hasMatch()) { if (matchAlt2.hasMatch()) {
@ -267,7 +267,7 @@ bool RegionMap::loadLayout(poryjson::Json layoutJson) {
this->layout_qualifiers = qualifiers + " " + type; this->layout_qualifiers = qualifiers + " " + type;
this->layout_array_label = label; this->layout_array_label = label;
QRegularExpression rowRe("{(?<row>[A-Z0-9_, ]+)}"); static const QRegularExpression rowRe("{(?<row>[A-Z0-9_, ]+)}");
QRegularExpressionMatchIterator k = rowRe.globalMatch(text); QRegularExpressionMatchIterator k = rowRe.globalMatch(text);
this->layout_layers.append("main"); this->layout_layers.append("main");
@ -779,7 +779,8 @@ QString RegionMap::fixCase(QString caps) {
bool big = true; bool big = true;
QString camel; QString camel;
for (auto ch : caps.remove(QRegularExpression("({.*})")).remove("MAPSEC")) { static const QRegularExpression re_braced("({.*})");
for (auto ch : caps.remove(re_braced).remove("MAPSEC")) {
if (ch == '_' || ch == ' ') { if (ch == '_' || ch == ' ') {
big = true; big = true;
continue; continue;

View file

@ -258,7 +258,7 @@ QString Tileset::getExpectedDir()
QString Tileset::getExpectedDir(QString tilesetName, bool isSecondary) QString Tileset::getExpectedDir(QString tilesetName, bool isSecondary)
{ {
QRegularExpression re("([a-z])([A-Z0-9])"); static const QRegularExpression re("([a-z])([A-Z0-9])");
const QString category = isSecondary ? "secondary" : "primary"; const QString category = isSecondary ? "secondary" : "primary";
const QString basePath = projectConfig.getFilePath(ProjectFilePath::data_tilesets_folders) + category + "/"; const QString basePath = projectConfig.getFilePath(ProjectFilePath::data_tilesets_folders) + category + "/";
return basePath + tilesetName.replace("gTileset_", "").replace(re, "\\1_\\2").toLower(); return basePath + tilesetName.replace("gTileset_", "").replace(re, "\\1_\\2").toLower();

View file

@ -261,7 +261,8 @@ void Editor::addNewWildMonGroup(QWidget *window) {
QLineEdit *lineEdit = new QLineEdit(); QLineEdit *lineEdit = new QLineEdit();
lineEdit->setClearButtonEnabled(true); lineEdit->setClearButtonEnabled(true);
form.addRow(new QLabel("Group Base Label:"), lineEdit); form.addRow(new QLabel("Group Base Label:"), lineEdit);
QRegularExpressionValidator *validator = new QRegularExpressionValidator(QRegularExpression("[_A-Za-z0-9]*")); static const QRegularExpression re_validChars("[_A-Za-z0-9]*");
QRegularExpressionValidator *validator = new QRegularExpressionValidator(re_validChars);
lineEdit->setValidator(validator); lineEdit->setValidator(validator);
connect(lineEdit, &QLineEdit::textChanged, [this, &lineEdit, &buttonBox](QString text){ connect(lineEdit, &QLineEdit::textChanged, [this, &lineEdit, &buttonBox](QString text){
if (this->project->encounterGroupLabels.contains(text)) { if (this->project->encounterGroupLabels.contains(text)) {

View file

@ -920,7 +920,8 @@ void Project::saveTilesetMetatileLabels(Tileset *primaryTileset, Tileset *second
} }
auto getTilesetFromLabel = [](QString labelName) { auto getTilesetFromLabel = [](QString labelName) {
return QRegularExpression("METATILE_(?<tileset>[A-Za-z0-9]+)_").match(labelName).captured("tileset"); static const QRegularExpression re_tilesetName("METATILE_(?<tileset>[A-Za-z0-9]+)_");
return re_tilesetName.match(labelName).captured("tileset");
}; };
QString outputText = "#ifndef GUARD_METATILE_LABELS_H\n"; QString outputText = "#ifndef GUARD_METATILE_LABELS_H\n";
@ -1410,10 +1411,12 @@ void Project::loadTilesetPalettes(Tileset* tileset) {
QString path = tileset->palettePaths.value(i); QString path = tileset->palettePaths.value(i);
QString text = parser.readTextFile(path); QString text = parser.readTextFile(path);
if (!text.isNull()) { if (!text.isNull()) {
QStringList lines = text.split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts); static const QRegularExpression re_lineBreak("[\r\n]");
QStringList lines = text.split(re_lineBreak, Qt::SkipEmptyParts);
if (lines.length() == 19 && lines[0] == "JASC-PAL" && lines[1] == "0100" && lines[2] == "16") { if (lines.length() == 19 && lines[0] == "JASC-PAL" && lines[1] == "0100" && lines[2] == "16") {
for (int j = 0; j < 16; j++) { for (int j = 0; j < 16; j++) {
QStringList rgb = lines[j + 3].split(QRegularExpression(" "), Qt::SkipEmptyParts); static const QRegularExpression re_space(" ");
QStringList rgb = lines[j + 3].split(re_space, Qt::SkipEmptyParts);
if (rgb.length() != 3) { if (rgb.length() != 3) {
logWarn(QString("Invalid tileset palette RGB value: '%1'").arg(lines[j + 3])); logWarn(QString("Invalid tileset palette RGB value: '%1'").arg(lines[j + 3]));
palette.append(qRgb((j - 3) * 16, (j - 3) * 16, (j - 3) * 16)); palette.append(qRgb((j - 3) * 16, (j - 3) * 16, (j - 3) * 16));
@ -1827,7 +1830,7 @@ bool Project::readTilesetLabels() {
logError(QString("Failed to read tileset labels from '%1' or '%2'.").arg(filename).arg(asm_filename)); logError(QString("Failed to read tileset labels from '%1' or '%2'.").arg(filename).arg(asm_filename));
return false; return false;
} }
QRegularExpression re("(?<label>[A-Za-z0-9_]*):{1,2}[A-Za-z0-9_@ ]*\\s+.+\\s+\\.byte\\s+(?<isSecondary>[A-Za-z0-9_]+)"); static const QRegularExpression re("(?<label>[A-Za-z0-9_]*):{1,2}[A-Za-z0-9_@ ]*\\s+.+\\s+\\.byte\\s+(?<isSecondary>[A-Za-z0-9_]+)");
QRegularExpressionMatchIterator iter = re.globalMatch(text); QRegularExpressionMatchIterator iter = re.globalMatch(text);
while (iter.hasNext()) { while (iter.hasNext()) {
QRegularExpressionMatch match = iter.next(); QRegularExpressionMatch match = iter.next();
@ -1986,7 +1989,8 @@ bool Project::readHealLocations() {
QString text = parser.readTextFile(root + "/" + filename); QString text = parser.readTextFile(root + "/" + filename);
// Strip comments // Strip comments
text.replace(QRegularExpression("//.*?(\r\n?|\n)|/\\*.*?\\*/", QRegularExpression::DotMatchesEverythingOption), ""); static const QRegularExpression re_comments("//.*?(\r\n?|\n)|/\\*.*?\\*/", QRegularExpression::DotMatchesEverythingOption);
text.replace(re_comments, "");
bool respawnEnabled = projectConfig.getHealLocationRespawnDataEnabled(); bool respawnEnabled = projectConfig.getHealLocationRespawnDataEnabled();
@ -1995,7 +1999,7 @@ bool Project::readHealLocations() {
this->healLocationDataQualifiers = this->getDataQualifiers(text, tableName); this->healLocationDataQualifiers = this->getDataQualifiers(text, tableName);
// Create regex pattern for the constants (ex: "SPAWN_PALLET_TOWN" or "HEAL_LOCATION_PETALBURG_CITY") // Create regex pattern for the constants (ex: "SPAWN_PALLET_TOWN" or "HEAL_LOCATION_PETALBURG_CITY")
QRegularExpression constantsExpr = QRegularExpression("(SPAWN|HEAL_LOCATION)_[A-Za-z0-9_]+"); static const QRegularExpression constantsExpr("(SPAWN|HEAL_LOCATION)_[A-Za-z0-9_]+");
// Find all the unique heal location constants used in the data tables. // Find all the unique heal location constants used in the data tables.
// Porymap doesn't care whether or not a constant appeared in the heal locations constants file. // Porymap doesn't care whether or not a constant appeared in the heal locations constants file.
@ -2304,13 +2308,16 @@ bool Project::readEventScriptLabels() {
} }
QString Project::fixPalettePath(QString path) { QString Project::fixPalettePath(QString path) {
path = path.replace(QRegularExpression("\\.gbapal$"), ".pal"); static const QRegularExpression re_gbapal("\\.gbapal$");
path = path.replace(re_gbapal, ".pal");
return path; return path;
} }
QString Project::fixGraphicPath(QString path) { QString Project::fixGraphicPath(QString path) {
path = path.replace(QRegularExpression("\\.lz$"), ""); static const QRegularExpression re_lz("\\.lz$");
path = path.replace(QRegularExpression("\\.[1248]bpp$"), ".png"); path = path.replace(re_lz, "");
static const QRegularExpression re_bpp("\\.[1248]bpp$");
path = path.replace(re_bpp, ".png");
return path; return path;
} }
@ -2416,7 +2423,8 @@ bool Project::readEventGraphics() {
QString subsprites_label = gfxInfoAttributes.value("subspriteTables"); QString subsprites_label = gfxInfoAttributes.value("subspriteTables");
QString gfx_label = parser.readCArray(projectConfig.getFilePath(ProjectFilePath::data_obj_event_pic_tables), pic_label).value(0); QString gfx_label = parser.readCArray(projectConfig.getFilePath(ProjectFilePath::data_obj_event_pic_tables), pic_label).value(0);
gfx_label = gfx_label.section(QRegularExpression("[\\(\\)]"), 1, 1); static const QRegularExpression re_parens("[\\(\\)]");
gfx_label = gfx_label.section(re_parens, 1, 1);
QString path = parser.readCIncbin(projectConfig.getFilePath(ProjectFilePath::data_obj_event_gfx), gfx_label); QString path = parser.readCIncbin(projectConfig.getFilePath(ProjectFilePath::data_obj_event_gfx), gfx_label);
if (!path.isNull()) { if (!path.isNull()) {
@ -2424,7 +2432,7 @@ bool Project::readEventGraphics() {
eventGraphics->spritesheet = QImage(root + "/" + path); eventGraphics->spritesheet = QImage(root + "/" + path);
if (!eventGraphics->spritesheet.isNull()) { if (!eventGraphics->spritesheet.isNull()) {
// Infer the sprite dimensions from the OAM labels. // Infer the sprite dimensions from the OAM labels.
QRegularExpression re("\\S+_(\\d+)x(\\d+)"); static const QRegularExpression re("\\S+_(\\d+)x(\\d+)");
QRegularExpressionMatch dimensionMatch = re.match(dimensions_label); QRegularExpressionMatch dimensionMatch = re.match(dimensions_label);
QRegularExpressionMatch oamTablesMatch = re.match(subsprites_label); QRegularExpressionMatch oamTablesMatch = re.match(subsprites_label);
if (oamTablesMatch.hasMatch()) { if (oamTablesMatch.hasMatch()) {

View file

@ -609,7 +609,7 @@ void MainWindow::setMetatileLabel(int metatileId, QString label) {
if (!metatile) if (!metatile)
return; return;
QRegularExpression expression("[_A-Za-z0-9]*$"); static const QRegularExpression expression("[_A-Za-z0-9]*$");
QRegularExpressionValidator validator(expression); QRegularExpressionValidator validator(expression);
int pos = 0; int pos = 0;
if (validator.validate(label, pos) != QValidator::Acceptable) { if (validator.validate(label, pos) != QValidator::Acceptable) {

View file

@ -18,7 +18,7 @@ AboutPorymap::~AboutPorymap()
QList<int> AboutPorymap::getVersionNumbers() QList<int> AboutPorymap::getVersionNumbers()
{ {
// Get the version string "#.#.#" // Get the version string "#.#.#"
QRegularExpression regex("Version (\\d+)\\.(\\d+)\\.(\\d+)"); static const QRegularExpression regex("Version (\\d+)\\.(\\d+)\\.(\\d+)");
QRegularExpressionMatch match = regex.match(ui->label_Version->text()); QRegularExpressionMatch match = regex.match(ui->label_Version->text());
if (!match.hasMatch()) { if (!match.hasMatch()) {
logError("Failed to locate Porymap version text"); logError("Failed to locate Porymap version text");

View file

@ -245,8 +245,10 @@ void NewMapPopup::on_pushButton_NewMap_Accept_clicked() {
// If map name is not unique, use default value. Also use only valid characters. // If map name is not unique, use default value. Also use only valid characters.
// After stripping invalid characters, strip any leading digits. // After stripping invalid characters, strip any leading digits.
QString newMapName = this->ui->lineEdit_NewMap_Name->text().remove(QRegularExpression("[^a-zA-Z0-9_]+")); static const QRegularExpression re_invalidChars("[^a-zA-Z0-9_]+");
newMapName.remove(QRegularExpression("^[0-9]*")); QString newMapName = this->ui->lineEdit_NewMap_Name->text().remove(re_invalidChars);
static const QRegularExpression re_NaN("^[0-9]*");
newMapName.remove(re_NaN);
if (project->mapNames.contains(newMapName) || newMapName.isEmpty()) { if (project->mapNames.contains(newMapName) || newMapName.isEmpty()) {
newMapName = project->getNewMapName(); newMapName = project->getNewMapName();
} }

View file

@ -11,7 +11,7 @@ NewTilesetDialog::NewTilesetDialog(Project* project, QWidget *parent) :
this->setFixedSize(this->width(), this->height()); this->setFixedSize(this->width(), this->height());
this->project = project; this->project = project;
//only allow characters valid for a symbol //only allow characters valid for a symbol
QRegularExpression expression("[_A-Za-z0-9]+$"); static const QRegularExpression expression("[_A-Za-z0-9]+$");
QRegularExpressionValidator *validator = new QRegularExpressionValidator(expression); QRegularExpressionValidator *validator = new QRegularExpressionValidator(expression);
this->ui->nameLineEdit->setValidator(validator); this->ui->nameLineEdit->setValidator(validator);

View file

@ -17,7 +17,7 @@ NoScrollComboBox::NoScrollComboBox(QWidget *parent)
this->completer()->setCompletionMode(QCompleter::PopupCompletion); this->completer()->setCompletionMode(QCompleter::PopupCompletion);
this->completer()->setFilterMode(Qt::MatchContains); this->completer()->setFilterMode(Qt::MatchContains);
QRegularExpression re("[^\\s]*"); static const QRegularExpression re("[^\\s]*");
QValidator *validator = new QRegularExpressionValidator(re); QValidator *validator = new QRegularExpressionValidator(re);
this->setValidator(validator); this->setValidator(validator);
} }

View file

@ -31,7 +31,7 @@ PreferenceEditor::~PreferenceEditor()
void PreferenceEditor::populateFields() { void PreferenceEditor::populateFields() {
QStringList themes = { "default" }; QStringList themes = { "default" };
QRegularExpression re(":/themes/([A-z0-9_-]+).qss"); static const QRegularExpression re(":/themes/([A-z0-9_-]+).qss");
QDirIterator it(":/themes", QDirIterator::Subdirectories); QDirIterator it(":/themes", QDirIterator::Subdirectories);
while (it.hasNext()) { while (it.hasNext()) {
QString themeName = re.match(it.next()).captured(1); QString themeName = re.match(it.next()).captured(1);

View file

@ -151,7 +151,7 @@ void RegionMapPropertiesDialog::accept() {
ui->message_alias->setText("alias cannot be empty"); ui->message_alias->setText("alias cannot be empty");
ui->message_alias->setVisible(true); ui->message_alias->setVisible(true);
} else { } else {
QRegularExpression re("[A-Za-z0-9_\\- ]+"); static const QRegularExpression re("[A-Za-z0-9_\\- ]+");
int temp = 0; int temp = 0;
QRegularExpressionValidator v(re, 0); QRegularExpressionValidator v(re, 0);

View file

@ -102,7 +102,7 @@ void ShortcutsEditor::populateMainContainer() {
QString ShortcutsEditor::getShortcutContext(const QObject *object) const { QString ShortcutsEditor::getShortcutContext(const QObject *object) const {
auto objectParentWidget = static_cast<QWidget *>(object->parent()); auto objectParentWidget = static_cast<QWidget *>(object->parent());
auto context = objectParentWidget->window()->objectName(); auto context = objectParentWidget->window()->objectName();
QRegularExpression re("[A-Z]"); static const QRegularExpression re("[A-Z]");
int i = context.indexOf(re, 1); int i = context.indexOf(re, 1);
while (i != -1) { while (i != -1) {
if (context.at(i - 1) != ' ') if (context.at(i - 1) != ' ')

View file

@ -164,7 +164,7 @@ void TilesetEditor::setAttributesUi() {
void TilesetEditor::setMetatileLabelValidator() { void TilesetEditor::setMetatileLabelValidator() {
//only allow characters valid for a symbol //only allow characters valid for a symbol
QRegularExpression expression("[_A-Za-z0-9]*$"); static const QRegularExpression expression("[_A-Za-z0-9]*$");
QRegularExpressionValidator *validator = new QRegularExpressionValidator(expression); QRegularExpressionValidator *validator = new QRegularExpressionValidator(expression);
this->ui->lineEdit_metatileLabel->setValidator(validator); this->ui->lineEdit_metatileLabel->setValidator(validator);
} }