3

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?

3 Answers 3

3

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")

1

To extract the text inside the brackets (), use this regular expression:

regexp_matches ( 
    post_office, 
    '(\\()(.+)(\\))'
)[1]

It works like this: Sri venkateswara puram (Sub Office) -> Sub Office


Explanation: how the expression works

The function regexp_matches() creates an array with the matches of the caputuring groups as the elements of the array:

  • (\\() finds opening bracket (
  • (.+) finds any number of characters
  • (\\)) finds closing bracket )

So for the example input Sri venkateswara puram (Sub Office), output of regexp_matches(...) will be the array [ '(', 'Sub Office', ')' ]. So opening and closing brackets are the first and last element of the array. You now want to get the second element of the array, so add the index in squarey brackets at the end. As index count starts at 0, type [1] to get the second element: Sub Office

1
  • 1
    I am not sure there is a need to capture the enclosing parentheses, at least the OP didn't mention it. If those aren't needed, the expression can be simplified a bit, so only a single item is matched and captured: '\\((.+)\\)'
    – bixb0012
    Feb 2, 2023 at 15:34
0

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

if( regexp_match( "fieldname",'criteria'), regexp_substr("fieldname",'criteria'),'')
2
  • This doesn't seem to work. Only outputs an empty string Mar 28, 2016 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, 2016 at 7:48

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.