[GIS] Using the regexp_substr function in QGIS to get the first letter after white space

qgisqgis-variable

I am looking to get the first letter and second letter (after white space) in the QGIS variable @user_full_name to provide me with the initials of the QGIS user that has created a project.

For instance, James Lewis > JL

My understanding is that the regexp_substr function can be used to achieve this, however I am not sure how the syntax should look to access the first character after the second white space.

Best Answer

Usually the project author is located under the @project_author, however, you can use the following expression to extract the initials of the project author, and it should be applied without a problem if you replace @project_author with @user_full_name. But in this example, I am using @project_author. Please make sure to adjust the start and length of the substr(string,start[,length]) based on string that you have.

@project_author || ': ' || '(' || substr(@project_author, 1,1) ||  substr(@project_author, 7,1) || ')'

Here is the input in expression:

enter image description here

Here is the output:

enter image description here

Update

If you want the initials to be created automatically, you need to create a custom function for it. You can use the following function to create the initials:

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

@qgsfunction(args='auto', group='Custom')
def nameInitial(text_field, feature, parent):
    split_text = text_field.split()
    initial = [nm[0] for nm in split_text]
    joinNM = "".join(initial)
    return joinNM

enter image description here

Then from Custom functions select the function the you created (nameInitial in this example) and @project_author.

enter image description here

The output is same as the above but without user adjustment:

@project_author || ': ' || '(' || nameInitial(@project_author ) || ')'

enter image description here