2

I'm trying to make a label ruled based. I have a numerical value:

123412341234

and try to write an expression to make it look like this:

1234-1234-1234

I tried using substr but I get an error when im trying to join two substr with dash between them.

substr("NTR_ID", 0, 4) + "-" + substr("NTR_ID", 5, 4)+ "-" + substr("NTR_ID", 9, 4)

What is the solution?

enter image description here

1
  • 3
    " are necessary when you want to refer to column names/fields, ' need to be used around strings.
    – Erik
    Nov 7, 2023 at 9:00

3 Answers 3

4

This expression here splits any string you insert in line 3 in groups of 4, connected with hyphen -. In line 3, you can also use a fieldname instead to convert the string in this input field:

with_variable (
    'your_string',
    '123412341234', -- insert string or fieldname here
    array_to_string (
        array_foreach(
            generate_series (1, length(@your_string),4),
            substr(@your_string, @element, 4)
        ), 
        '-'
    )
)

enter image description here

3

You are incorrectly using double quotes instead of single quotes for string literals. Please read the QGIS user manual about writing expressions https://docs.qgis.org/3.28/en/docs/user_manual/expressions/expression.html#writing-an-expression

The correct expression is the following one:

substr("NTR_ID", 0, 4) + '-' + substr("NTR_ID", 5, 4) + '-' + substr("NTR_ID", 9, 4)

2

For splitting inputs with fixed length (here: 12 characters), use this expression ("input_text" is the name of the field containing the string you want to format):

array_to_string (
    regexp_matches ("input_text",'(.{4})(.{4})(.{4})'),
    '-'
)

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.