I have a shapefile with polygons containing UK postcode units, example SL1 1AA. I want to dissolve these into postcode sectors,example SL1 1.

enter image description here

I can use this expression in the filter to get all those postcode units in one sector and dissolve that as the image above.

LIKE 'SL1 1%%'

What i want to do is apply a similar expression with dissolve altering the expression to a regex so it dissolves into SL1 1, SL1 2 etc.

I have an idea how i could tackle this in postgis but wanted to see if i could do this with the QGIS

2 Answers 2


if you want this to work anywhere in the UK, there are several formats

the following regex :-


should match the 6 possible patterns

  • EC1A 1BB
  • W1A 0AX
  • M1 1AE
  • B33 8TH
  • CR2 6XH
  • DN55 1PT

The following works, assuming your field is called pcd.

You can use the regexp_substr() function in QGIS expressions, but this won't work unless

  • there is an outer group (i.e. brackets around the whole expression)
  • backslashes are doubled (to escape them)

You can use this expression to extract the bit you want


I found a few which didn't match, I'm not sure where I got the data from (either OS or ONS; the latter includes lots of expired postcodes which may explain some discrepancies)

A simpler way (and probably faster too, with large datasets) is to simply find the space and take everything up to and including the character after it

 left("pcd" ,strpos("pcd",' ')+1)
  • Thank you, opted for the regex which works well on the official OS set. I'm running whole of Eng Wales so will test the two approaches Jul 31, 2017 at 17:17

Open field calculator and make a new field with the expression left(postcode, 5) Then use the dissolve tool. In the tools' form, uncheck "dissolve all" and use the new field to dissolve by.

  • Thank you, i used this in conjunction with @Steven Kays answer Aug 2, 2017 at 7:53

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.