Use Regex to identify patterns in UK Postcodes

264 Views Asked by At

For any UK postal code I want to replace all letters with capital A and all digits with 9.

For example CH5 1EF would become AA9 9AA EC1N 4DH would become AA9A 9AA

Is this possible in a single RegEx.Replace or would I have to have two separate RegEx.Replace statements?

2

There are 2 best solutions below

0
On BEST ANSWER

You haven't said what language you are using, I'll just give the regex.

Two operations:

  1. Matching regex: [A-Z] and replace with: A
  2. Matching regex: \d and replace with: 9

In java, it would look like:

String postcode = "CH5 1EF";
String result = postcode.replaceAll("[A-Z]", "A").replaceAll("\\d", "9");
0
On

You'd need two replaces for this: first replace all [A-Za-z] with "A" then replace all [0-9] with "9". Even if there was a way to do this with a single expression it would be a nightmare to read and maintain it.