Search code examples
regexreplacepostal-code

Use Regex to identify patterns in UK Postcodes


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?


Solution

  • 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");