Skip to content
Permalink
Browse files

Fix regex used to replace [% %] expressions in text

Was incorrectly truncating at first ']' character

Fixes #21366

(cherry picked from commit cab2dcf)
  • Loading branch information
nyalldawson committed Feb 25, 2019
1 parent a95f872 commit d966d9c71cfc8e3c95236043146eacdfa4b11fe9
Showing with 29 additions and 8 deletions.
  1. +9 −8 src/core/expression/qgsexpression.cpp
  2. +20 −0 tests/src/core/testqgsexpression.cpp
@@ -474,18 +474,19 @@ QString QgsExpression::replaceExpressionText( const QString &action, const QgsEx
int index = 0;
while ( index < action.size() )
{
QRegExp rx = QRegExp( "\\[%([^\\]]+)%\\]" );
static const QRegularExpression sRegEx{ QStringLiteral( "\\[%(.*?)%\\]" ) };

int pos = rx.indexIn( action, index );
if ( pos < 0 )
const QRegularExpressionMatch match = sRegEx.match( action, index );
if ( !match.hasMatch() )
break;

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

QgsExpression exp( to_replace );
QgsExpression exp( toReplace );
if ( exp.hasParserError() )
{
QgsDebugMsg( "Expression parser error: " + exp.parserErrorString() );
@@ -3404,6 +3404,26 @@ class TestQgsExpression: public QObject
QCOMPARE( zustaendigkeitskataster->dataProvider()->featureCount(), 4l );
}

void testReplaceExpressionText_data()
{
QTest::addColumn<QString>( "input" );
QTest::addColumn<QString>( "expected" );
QTest::newRow( "no exp" ) << "some text" << "some text";
QTest::newRow( "simple exp" ) << "some text [% 1 + 2 %]" << "some text 3";
QTest::newRow( "multiple exp" ) << "some [% 3+ 7 %] text [% 1 + 2 %]" << "some 10 text 3";
QTest::newRow( "complex" ) << "some [%map('a', 1, 'b', 2)['a']%] text [%map('a', 1, 'b', 2)['b']%]" << "some 1 text 2";
QTest::newRow( "complex2" ) << "some [% 'my text]' %] text" << "some my text] text";
}

void testReplaceExpressionText()
{
QFETCH( QString, input );
QFETCH( QString, expected );

QgsExpressionContext context;
QCOMPARE( QgsExpression::replaceExpressionText( input, &context ), expected );
}

};

QGSTEST_MAIN( TestQgsExpression )

0 comments on commit d966d9c

Please sign in to comment.
You can’t perform that action at this time.