Geographic Information Systems Asked by Zac on February 4, 2021
I hope to use QgsFeatureRequest(QgsExpression)
to get desired features.
The statement in QgsExpression is:
expr = QgsFeatureRequest(QgsExpression(""planid" in (48757) AND spi like '0%'")
The feature has "planid" = 48757
, and "spi"
field is string like '0abcdefg'
.
So I intended to match '0'
in the QgsExpression
, but it didn’t work at all. I got nothing returned.
If I changed the string to ""planid" in (48757) AND spi like '0%'"
by removing ''
, then it could return a feature.
But I really need ''
, since it’s a very important character.
So how should I modify the string to make it work?
UPDATE:
From @MatthiasKuhn suggestion, I tested to use ‘\’ in QgsExpression, like ""planid" in (48757) AND spi like '0\%'"
.
It didn’t work from Python scripts, but I did get a hint from it. After running the statement from "Select by Expression" in QGIS, four ” worked fine. So this is the correct format.
Therefore, I built the statement in Python with 8 ”, and it did work.
expr = QgsFeatureRequest(QgsExpression(""planid" in (48757) AND spi like '0\\%'")
I understand why Python needs to double the number of ”, but can @MatthiasKuhn or anyone else explain why I need four ” here in QGIS?
A stands for an escape character in many contexts and changes the meaning of the following character. E.g.
n
often means newline, t
tab. To actually write the itself. To actually make us of a
it has to be escaped itself to
.
This is for example the case for a LIKE operator which uses a regular expression engine which needs escape. Double the backslash
.
However, before it arrives in the regular expression, it also traverses the QGIS expression parser where it needs to be escaped too. Double it
\
.
However, since you are using python to create this, python already needs to escape things. Which means escaping each single again. Double it
\\
.
Answered by Matthias Kuhn on February 4, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP