Splitting text from a string field before each delimiter to new fields

EDIT: I edited the answer according to some comments by JWes.


You may run a simple script from the Python Console. Firstly, open the Python Console from Plugins > Python Console and activate the button for the Editor:

enter image description here

Then, load the object (a vector, a table, etc.) where your data are stored.

Once you have done this, copy the following code in the Editor:

layer = iface.activeLayer()
fieldindex = layer.fieldNameIndex("Tasks")
layer.startEditing()
for feat in layer.getFeatures():
    if feat[fieldindex]:
        fields = feat[fieldindex].split('.')
        for i in range(1, len(fields)):
            feat[fieldindex + i] = fields[i - 1]
            layer.updateFeature(feat)
    else:
        continue
layer.commitChanges()

and then run it:

enter image description here

You will obtain this:

enter image description here

If you prefer, you may obviously use the above code as a Python function for the field calculator (I saw that you already know how to do it).


This is not a very efficient method but is one I used before. Make sure Field2 and Field3 exist then use something like the following:

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

@qgsfunction(args='auto', group='Custom')
def func(field, feature, parent):
    # Get active layer
    layer = qgis.utils.iface.activeLayer()
    # Get field indices
    idx_2 = layer.fieldNameIndex('Field2')
    idx_3 = layer.fieldNameIndex('Field3')
    # Extract string values
    first_value = [w for w in re.split('\W', field) if w][0]
    second_value = [w for w in re.split('\W', field) if w][1]
    third_value = [w for w in re.split('\W', field) if w][2]    
    # Update values in fields
    layer.changeAttributeValue(feature.id(), idx_2, second_value)
    layer.changeAttributeValue(feature.id(), idx_3, third_value)
    return first_value

Example:

  1. Here is an attribute:

    Attribute table

  2. Then once your script has been saved, select to update Field1 and use the expression:

    func("Field1")
    

    Function editor

  3. Result:

    Result