I have a gpkg with a column called name. I am trying to use PyQGIS to find any of the values in this column that starts with r and then contain e or x. I would then like to update a new column I've created called Relevant_Pipework with either Relevant or Not Relevant based on whether the regex has matched. Below is the code I've written.

import re
from qgis.core import (

path_to_gpkg = "D:/Pipework.gpkg"

Water_Pipes_Layer = path_to_gpkg + "|Water_Pipes"

vlayer = QgsVectorLayer(Water_Pipes_Layer, "Water_Pipes", "ogr")
if not vlayer.isValid():
    print("Layer failed to load!")

layer = iface.activeLayer()
prov = layer.dataProvider()
pattern = '[rex]'

features = layer.getFeatures()


if layer.dataProvider().fieldNameIndex("Relevant_Pipework") == -1:
    layer.dataProvider().addAttributes([QgsField("Relevant_Pipework", QVariant.String)])

for feat in features:
    Regex_Search_Field = feature['name']
    Regex_String = re.compile(pattern)
    Regex_Match = Regex_String.search(Regex_Search_Field)
    if Regex_Match:
        layer.changeAttributeValue(feat.id(), 11, "Match")
        layer.changeAttributeValue(feat.id(), 11, "No Match")

1 Answer 1


I think your regex needs to be ^r.*[ex].*$ - In general it's always worth using a regex tester like https://regex101.com/ to try these out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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