Skip to content

Commit

Permalink
Add method to search variables in text with expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
pblottiere committed Apr 26, 2018
1 parent 201f108 commit 4168c05
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
9 changes: 9 additions & 0 deletions python/core/expression/qgsexpression.sip.in
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,15 @@ Additional substitutions can be passed through the substitutionMap parameter
and area conversion

.. versionadded:: 2.12
%End

static QSet<QString> referencedVariables( const QString &text );
%Docstring
This function returns variables in each expression between [% and %].

:param text: The source string in which variables should be searched.

.. versionadded:: 3.2
%End

static double evaluateToDouble( const QString &text, const double fallbackValue );
Expand Down
23 changes: 23 additions & 0 deletions src/core/expression/qgsexpression.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,29 @@ QString QgsExpression::replaceExpressionText( const QString &action, const QgsEx
return expr_action;
}

QSet<QString> QgsExpression::referencedVariables( const QString &text )
{
QSet<QString> variables;
int index = 0;
while ( index < text.size() )
{
QRegExp rx = QRegExp( "\\[%([^\\]]+)%\\]" );

int pos = rx.indexIn( text, index );
if ( pos < 0 )
break;

int start = index;
index = pos + rx.matchedLength();
QString to_replace = rx.cap( 1 ).trimmed();

QgsExpression exp( to_replace );
variables.unite( exp.referencedVariables() );
}

return variables;
}

double QgsExpression::evaluateToDouble( const QString &text, const double fallbackValue )
{
bool ok;
Expand Down
9 changes: 9 additions & 0 deletions src/core/expression/qgsexpression.h
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,15 @@ class CORE_EXPORT QgsExpression
static QString replaceExpressionText( const QString &action, const QgsExpressionContext *context,
const QgsDistanceArea *distanceArea = nullptr );

/**
* This function returns variables in each expression between [% and %].
*
* \param text The source string in which variables should be searched.
*
* \since QGIS 3.2
*/
static QSet<QString> referencedVariables( const QString &text );

/**
* Attempts to evaluate a text string as an expression to a resultant double
* value.
Expand Down

0 comments on commit 4168c05

Please sign in to comment.