Skip to content

Commit 4168c05

Browse files
committed
Add method to search variables in text with expressions
1 parent 201f108 commit 4168c05

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

python/core/expression/qgsexpression.sip.in

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,15 @@ Additional substitutions can be passed through the substitutionMap parameter
369369
and area conversion
370370

371371
.. versionadded:: 2.12
372+
%End
373+
374+
static QSet<QString> referencedVariables( const QString &text );
375+
%Docstring
376+
This function returns variables in each expression between [% and %].
377+
378+
:param text: The source string in which variables should be searched.
379+
380+
.. versionadded:: 3.2
372381
%End
373382

374383
static double evaluateToDouble( const QString &text, const double fallbackValue );

src/core/expression/qgsexpression.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,29 @@ QString QgsExpression::replaceExpressionText( const QString &action, const QgsEx
477477
return expr_action;
478478
}
479479

480+
QSet<QString> QgsExpression::referencedVariables( const QString &text )
481+
{
482+
QSet<QString> variables;
483+
int index = 0;
484+
while ( index < text.size() )
485+
{
486+
QRegExp rx = QRegExp( "\\[%([^\\]]+)%\\]" );
487+
488+
int pos = rx.indexIn( text, index );
489+
if ( pos < 0 )
490+
break;
491+
492+
int start = index;
493+
index = pos + rx.matchedLength();
494+
QString to_replace = rx.cap( 1 ).trimmed();
495+
496+
QgsExpression exp( to_replace );
497+
variables.unite( exp.referencedVariables() );
498+
}
499+
500+
return variables;
501+
}
502+
480503
double QgsExpression::evaluateToDouble( const QString &text, const double fallbackValue )
481504
{
482505
bool ok;

src/core/expression/qgsexpression.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,15 @@ class CORE_EXPORT QgsExpression
400400
static QString replaceExpressionText( const QString &action, const QgsExpressionContext *context,
401401
const QgsDistanceArea *distanceArea = nullptr );
402402

403+
/**
404+
* This function returns variables in each expression between [% and %].
405+
*
406+
* \param text The source string in which variables should be searched.
407+
*
408+
* \since QGIS 3.2
409+
*/
410+
static QSet<QString> referencedVariables( const QString &text );
411+
403412
/**
404413
* Attempts to evaluate a text string as an expression to a resultant double
405414
* value.

0 commit comments

Comments
 (0)