Saturday, 24 March 2018

Remove Leading Zeros with QGIS Field Calculator



I'd like to take this attribute value: "MAP_PAR_ID": "0160011000", and populate a new field with "16-11".


This works: concat(substr("MAP_PAR_ID",0,3), '-', substr("MAP_PAR_ID",5,3)) but i need to detect leading zeros and not include them


I've tried numerous variations of CASE ELSE statements but can't even detect leading zeros. Feeble attempt below:


CASE
WHEN substr("MAP_PAR_ID", 0, 1) = '0' THEN substr("MAP_PAR_ID", 1, 2)
ELSE substr("MAP_PAR_ID", 0, 3)

WHEN substr("MAP_PAR_ID", 5, 1) = '0' THEN substr("MAP_PAR_ID", 6, 2)
ELSE substr("MAP_PAR_ID",5, 3)
END


Would the python console make things a little easier?



Answer



You can use a regex replace for this:


 regexp_replace('0160011000', '0+([1-9]+)0+([1-9]+)0+', '\\1-\\2')
regexp_replace("MAP_PAR_ID", '0+([1-9]+)0+([1-9]+)0+', '\\1-\\2')

The regex is broken down like this:



  • 0+ - Any number of zeros at the start


  • ([1-9]+) - Any number of values between 1 and 9. Capture into group 1

  • 0+ - Any number of zeros in the middle

  • ([1-9]+) - Any number of values between 1 and 9. Capture into group 2

  • 0+ - Any number of zeros at the end


The regex_replace function is defined like this:


regexp_replace(string,regex,after) 

So in the after section we use \\1-\\2 to add the values from group 1 and 2 into our new string.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...