I am learning to use Python scripts to automate tasks in my work. I am a beginner in Python and PyQGIS.

I would like to select entities in a layer using regexp_match. It works well in QGIS but I can't transpose it into the Python script.

Could someone tell me how to do it?

Here is my current code:

query = "regexp_match(\"COD\" ,'\d.\d\d')"
selshp = shp.getFeatures(QgsFeatureRequest().setFilterExpression(query))
shp.setSelectedFeatures([f.id() for f in selshp])

But no entities are selected while in QGIS I have 670 selected entities.


Try with this code :

query = "regexp_match(\"COD\", '\\\\d.\\\\d\\\\d')"
selshp = shp.getFeatures(QgsFeatureRequest().setFilterExpression(query))
shp.modifySelection([f.id() for f in selshp], [])
  • '\d' : normal regular expression for digits
  • '\\d' : this regular expression under QGIS
  • '\\\\d' : again under Python for escape special characters.
  • I made a mistake in the posted code, I wrote it like this '\\d' in the script but I haven't think to write it in Python language with escape char – Kinad May 28 at 13:55

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.