I Have a CSV table where one of the columns has names of the post offices with the type given in brackets like this:

Sri venkateswara puram (Sub Office)

I want to extract the post office type, by using regular expressions, and I can use (?<=\().+?(?=\)) as the regular expression, but I can't figure out how I can copy the matching string to another column in Qgis's Field Calculator.

How do I extract the match of a Regular Expression in Qgis's Field Calculator, either using the inbuilt functions or custom functions?


I solved this issue by writing the following custom function

Define new functions using @qgsfunction. feature and parent must always be the
last args. Use args=-1 to pass a list of values as arguments

from qgis.core import *
from qgis.gui import *
import re

@qgsfunction(args='auto', group='Custom')
def getRegexMatch(s, feature, value):
    p = re.compile(ur'(?<=\().+?(?=\))')
    result=re.findall(p, s)
    return result[-1]

After I loaded this function, I could populate the required column with the following expression getRegexMatch("Name")


Another shorter alternative would be to use the build in "if" function.

if( regexp_match( "fieldname",'criteria'), regexp_substr("fieldname",'criteria'),'')

  • This doesn't seem to work. Only outputs an empty string – Devdatta Tengshe Mar 28 '16 at 7:18
  • Misunderstoof your question at first, Edited the answer with the regexp_substr as output of the function. But you are right it is not working, possibly this built in function does not allow the full regexp vocabulary. – Matte Mar 28 '16 at 7:48

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.