Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
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 26, 2019
1 parent 38a3b2a commit 1ef89f2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/core/expression/qgsexpression.cpp
Expand Up @@ -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() );
Expand Down
19 changes: 19 additions & 0 deletions tests/src/core/testqgsexpression.cpp
Expand Up @@ -3203,6 +3203,25 @@ class TestQgsExpression: public QObject

QCOMPARE( v.toDateTime().toMSecsSinceEpoch(), v2.toDateTime().toMSecsSinceEpoch() );
}

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( "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 )
Expand Down

0 comments on commit 1ef89f2

Please sign in to comment.