if you want this to work anywhere in the UK, there are several formats
the following regex :-
[A-Z]{1,2}[A\d+[A-Z]?\d+\s\d\s\d
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
regexp_substr("pcd",'([A-Z]{1,2}\\d+[A-Z]?\\s\\d)')
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)