There are 6 possible formats for postcodes in the UK:
- A9 9AA
- A9A 9AA
- A99 9AA
- AA9 9AA
- AA9A 9AA
- AA99 9AA
I think there need to be two parts to your solution. The first is to validate the input; the second is to grab that first part.
Validation
This is really important, even though I realise you have said this is not what you are trying to do, but without it you are going to struggle to get the right prefix and possibly send your drivers to the wrong place!
There are a couple of ways you can do it, either use a 3rd party to help you capture a complete & correct address (many available including http://www.qas.co.uk/knowledge-centre/product-information/address-postcode-finder.htm (my company)), or at a minimum use some reg-ex / similar sanity testing to validate the postcodes - such as the links Dmitri gave you above.
If you look at the test cases you have listed - W1ABC and W10ABC are not valid postcodes - if we get that bit correct then the next bit becomes a lot easier.
Extract the Prefix
Assuming you now have a full, valid postcode getting just the first part (outcode) becomes a lot easier - with or without spaces. Because the second half (incode) has a standard format of 9AA, digit-alpha-alpha, I would do it by spotting and removing this, leaving you with just your outcode whether it be W1 From W1 0AA, or W10 from W10 0AA.
Alternatively, if you are using a 3rd party to capture the address - most of them will be able to return the incode and outcode separately for you.