2

In QGIS 3.X, I'm attempting to use an expression in layout composer to automatically input the client and project name into a text box. The details are always present in the file path to the project as you can see below. The number of backslashes will not change and the client name will always be between the 8th & 9th. Likewise, the project name follows the project number (which should be omitted from the expression.) A snip from the layout composer of how the text box should look is below.

C:\Users\user\Dropbox\Encrypted\GIS\1. Client Projects\S\Smith, S\ABC999999 - Site Finding, England

enter image description here

0

You'll want to use regex to parse that string, which is handily available in QGIS as the function regex_substr().

Assuming your name always follows the project number in the format you've given (i.e. separated by a space, -, and another space), you can try the following expression:

regexp_substr(@project_folder,
'^(?:[^\\\\]+\\\\){8}([^\\\\]+)(?:\\\\)') || ' / ' || 
regexp_substr(@project_folder,
'^(?:[^\\\\]+\\\\){9}(?:\\w+ - )([^\\\\]+)')

The first part extracts the client name. The bit up to and including the number with the curly brackets looks for:

  • 8 instances ({8}) of a non-capturing group (indicated by ?:) with the following pattern:

    • Anything but a backslash ([^\\\\])
    • any number of times (+)
    • until a backslash is hit (\\\\)
    • that's your 8 folders before the one you want.
  • Then it extracts the folder name

    • i.e., again, anything but a backslash any number of times ([^\\\\])
    • until it hits another (optional) backslash (?:\\\\)

This is then concatenated with a forward slash and spaces (|| ' / ' ||)

Followed by the project name, which is much like the above, except it looks for

  • 9 instances of anything + backslash
  • followed by another non-capturing group of
    • any non-whitespace characters
    • followed by a space, - symbol, and space
    • which is your project number: (?:\\w+ - )
  • and then, again, anything but a backslash any number of times ([^\\\\])
    • this is your project name.

Note that backslashes are escaped in normal expression editing in QGIS by doubling them up, and use of regex functions requires the same, so to convey the backslash character in regexp_substr() and similar functions, backslashes must be typed as \\\\

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.