QGIS – Automatic Fill of Attribute Table by Expression

attribute-tableexpressionfield-calculatorqgisstring

I have a line layer and in the attribute list the "Name" column, which can be, for example, 'V1','V2',….'V1-2','V1-2-3',… in I'm trying to put an expression in the next column that is essentially only '1' or '2' or '3' and that:

  • 1 – when the name is without '-', i.e. 'V1' or 'V2' or 'V3'
  • 2 – when it has only one '-', for example 'V2-3', 'V10-1' and so on
  • other variants should be marked as '3'.

I tried:

If( "NameVlake" like '%-%',If( "NameVlake" like '%-%-%',If( "NameVlake" like '%-%-%-%',If( "NameVlake" like '% -%-%-%-%',If( "Train Name" like '%-%-%-%-%-%',3),3),3),2),1)

even this

CASE
WHEN "name" LIKE '%-__%' THEN '3'
WHEN "name" LIKE '%-_%' THEN '2'
ELSE '1'
end

I didn't succeed.


EDIT:
@Mayo
I tried to enter your code as the default value in the Attribute form

CASE
   WHEN array_length(string_to_array("name", '-')) = 1 THEN 1
   WHEN array_length(string_to_array("name", '-')) = 2 THEN 2
   ELSE 3
END

but everything is marked as '3'…

It might be important (!?) the "Name" column is a string, as well as the "Order" column
enter image description here

Best Answer

Try:

CASE
   WHEN array_length(string_to_array("name", '-')) = 1 THEN 1
   WHEN array_length(string_to_array("name", '-')) = 2 THEN 2
   ELSE 3
END
Related Question