Skip to content

Commit cab2dcf

Browse files
committed
Fix regex used to replace [% %] expressions in text
Was incorrectly truncating at first ']' character Fixes #21366
1 parent a615a3b commit cab2dcf

File tree

2 files changed

+29
-8
lines changed

2 files changed

+29
-8
lines changed

src/core/expression/qgsexpression.cpp

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -474,18 +474,19 @@ QString QgsExpression::replaceExpressionText( const QString &action, const QgsEx
474474
int index = 0;
475475
while ( index < action.size() )
476476
{
477-
QRegExp rx = QRegExp( "\\[%([^\\]]+)%\\]" );
477+
static const QRegularExpression sRegEx{ QStringLiteral( "\\[%(.*?)%\\]" ) };
478478

479-
int pos = rx.indexIn( action, index );
480-
if ( pos < 0 )
479+
const QRegularExpressionMatch match = sRegEx.match( action, index );
480+
if ( !match.hasMatch() )
481481
break;
482482

483-
int start = index;
484-
index = pos + rx.matchedLength();
485-
QString to_replace = rx.cap( 1 ).trimmed();
486-
QgsDebugMsg( "Found expression: " + to_replace );
483+
const int pos = action.indexOf( sRegEx, index );
484+
const int start = index;
485+
index = pos + match.capturedLength( 0 );
486+
const QString toReplace = match.captured( 1 ).trimmed();
487+
QgsDebugMsg( "Found expression: " + toReplace );
487488

488-
QgsExpression exp( to_replace );
489+
QgsExpression exp( toReplace );
489490
if ( exp.hasParserError() )
490491
{
491492
QgsDebugMsg( "Expression parser error: " + exp.parserErrorString() );

tests/src/core/testqgsexpression.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3418,6 +3418,26 @@ class TestQgsExpression: public QObject
34183418
QCOMPARE( zustaendigkeitskataster->dataProvider()->featureCount(), 4l );
34193419
}
34203420

3421+
void testReplaceExpressionText_data()
3422+
{
3423+
QTest::addColumn<QString>( "input" );
3424+
QTest::addColumn<QString>( "expected" );
3425+
QTest::newRow( "no exp" ) << "some text" << "some text";
3426+
QTest::newRow( "simple exp" ) << "some text [% 1 + 2 %]" << "some text 3";
3427+
QTest::newRow( "multiple exp" ) << "some [% 3+ 7 %] text [% 1 + 2 %]" << "some 10 text 3";
3428+
QTest::newRow( "complex" ) << "some [%map('a', 1, 'b', 2)['a']%] text [%map('a', 1, 'b', 2)['b']%]" << "some 1 text 2";
3429+
QTest::newRow( "complex2" ) << "some [% 'my text]' %] text" << "some my text] text";
3430+
}
3431+
3432+
void testReplaceExpressionText()
3433+
{
3434+
QFETCH( QString, input );
3435+
QFETCH( QString, expected );
3436+
3437+
QgsExpressionContext context;
3438+
QCOMPARE( QgsExpression::replaceExpressionText( input, &context ), expected );
3439+
}
3440+
34213441
};
34223442

34233443
QGSTEST_MAIN( TestQgsExpression )

0 commit comments

Comments
 (0)