|
1 | 1 | /* |
2 | | - * Copyright (C) 2023 Nick Egorrov, nicegorov@yandex.ru |
| 2 | + * Copyright (C) 2023-2023 Nick Egorrov, nicegorov@yandex.ru |
3 | 3 | * |
4 | 4 | * This file is part of GCodeWorkShop. |
5 | 5 | * |
|
17 | 17 | * along with this program. If not, see <http://www.gnu.org/licenses/>. |
18 | 18 | */ |
19 | 19 |
|
20 | | -#include <QRegularExpression> // for QRegularExpression |
21 | | -#include <QString> // for QString |
22 | | -#include <QStringList> // for QStringList |
| 20 | +#include <QRegularExpression> // for QRegularExpression |
| 21 | +#include <QRegularExpressionMatch> // for QRegularExpressionMatch |
| 22 | +#include <QRegularExpressionMatchIterator> // for QRegularExpressionMatchIterator |
| 23 | +#include <QString> // for QString |
| 24 | +#include <QStringList> // for QStringList |
23 | 25 |
|
24 | 26 | #include "utils-removebyregex.h" |
25 | 27 |
|
26 | 28 |
|
27 | | -bool Utils::removeTextByRegExp(QString& tx, QStringList expList, bool replaceDollar) |
| 29 | +bool Utils::removeTextByRegExp(QString& tx, |
| 30 | + const QStringList& expList, |
| 31 | + bool replaceDollar, |
| 32 | + const std::function<bool (int)>& interrupt) |
28 | 33 | { |
29 | 34 | if (expList.isEmpty()) { |
30 | 35 | return false; |
31 | 36 | } |
32 | 37 |
|
33 | | - for (QString regexp : expList) { |
34 | | - if (replaceDollar && regexp.contains('$') && !regexp.contains("\\$")) { |
35 | | - regexp.replace('$', "\\n"); |
| 38 | + QString complex; |
| 39 | + |
| 40 | + // Glue multiple regular expressions into one. |
| 41 | + for (QString exp : expList) { |
| 42 | + if (replaceDollar && exp.contains('$') && !exp.contains("\\$")) { |
| 43 | + exp.replace('$', "\\n"); |
| 44 | + } |
| 45 | + |
| 46 | + if (!complex.isEmpty()) { |
| 47 | + complex.append("|"); |
| 48 | + } |
| 49 | + |
| 50 | + complex.append(exp); |
| 51 | + } |
| 52 | + |
| 53 | + QRegularExpression regexpr{ |
| 54 | + complex, |
| 55 | + QRegularExpression::CaseInsensitiveOption |
| 56 | + }; |
| 57 | + QRegularExpressionMatchIterator iterator = regexpr.globalMatch(tx); |
| 58 | + |
| 59 | + int pos = 0; |
| 60 | + QString result; |
| 61 | + |
| 62 | + while (iterator.hasNext()) { |
| 63 | + if (interrupt(pos)) { |
| 64 | + return false; |
36 | 65 | } |
37 | 66 |
|
38 | | - tx.remove(QRegularExpression(regexp)); |
| 67 | + const QRegularExpressionMatch& match = iterator.next(); |
| 68 | + const QString& sub = tx.mid(pos, match.capturedStart() - pos); |
| 69 | + result.append(sub); |
| 70 | + pos = match.capturedEnd(); |
39 | 71 | } |
40 | 72 |
|
| 73 | + result.append(tx.mid(pos)); |
| 74 | + tx = result; |
41 | 75 | return true; |
42 | 76 | } |
0 commit comments