Dave Poole
Dave Poole

Reputation: 1068

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?

Upvotes: 2

Views: 270

Answers (2)

Brian Rogers
Brian Rogers

Reputation: 129687

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.

Upvotes: 0

Bohemian
Bohemian

Reputation: 424993

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

Upvotes: 2

Related Questions