2

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 '0\abcdefg' .

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?

3
  • 2
    Did you try to double up the \ in the like part to 0\\\\% ? Nov 2 '20 at 7:40
  • Hi @MatthiasKuhn, I tried 0\\\\% and 0\\\% and 0\\% and 0\% . None of them worked.
    – Zac
    Nov 2 '20 at 10:32
  • Hi @MatthiasKuhn, I updated my question. Can you tell me why there is four '\' here. And could you answer the question instead of comment, so I can accept it. Thank you.
    – Zac
    Nov 2 '20 at 11:51
1

Escape character

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 \\\\\\\\.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.