Reformat string containing uk postcode using regex

uk postcode regex
uk postcode regex c#
uk postcode regex javascript
the value does not match the pattern a9 9aa a99 9aa aa9 9aa aa99 9aa aa9a 9aa a9a 9aa 9999 99999

How can I format a string using Javascript to match a regex?

I am using UK postcodes which could match any of the following

N1 3LD
GU34 8RR

I have the following regex which validates a string correctly, but I am unsure how to use the regex as a mask to format EC1A3AD to EC1A 3AD / GU348RR to GU34 8RR / N13LD to N1 3LD.

My regex is /^[A-Za-z]{1,2}[0-9A-Za-z]{1,2}[ ]?[0-9]{0,1}[A-Za-z]{2}$/

Thank you

If you use the regular expression /^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/ you can extract the two parts of the postcode and reassemble them with an intervening space.

var list = ['N13LD', 'EC1A3AD', 'GU348RR'];

for (var i = 0; i < list.length; i++) {
  var parts = list[i].match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/);
  alert(parts.join(' '));


N1 3LD
GU34 8RR

Java Regex - UK Postcode Validation, Learn to use regular expressions for UK postcode validation in Java. You can modify the regex to suit it for any other format such as US postal codes. can appear at particular positions are little complicated and filled with exception cases. String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$" ;​. I've been working on a regex-based UK postcode validation and format correction tool - with the aim of creating a list of postcodes that can be readily geocoded. The variety of postcode formats is explained here. I have based my regex on a discussion here.

Put braces around the bits separated by the optional space:

/^([A-Za-z]{1,2}[0-9A-Za-z]{1,2})[ ]?([0-9]{0,1}[A-Za-z]{2})$/

However I think the regexp is wrong... The above regexp splits "N13LD" as "N13", "LD".

I suspect the errant part is the {0,1} before the two trailing letters - there must AFAIK be exactly one digit there:

var re = /^([A-Z]{1,2}[\dA-Z]{1,2})[ ]?(\d[A-Z]{2})$/i; // case insensitive

The grouping allows the string.match(regexp) function to return a result which includes an entry for each matching group:

> "N13LD".match(re);
["N13LD", "N1", "3LD"]

> "GU348RR".match(re);
["GU348RR", "GU34", "8RR"]

> "EC1A3AD".match(re);
["EC1A3AD", "EC1A", "3AD"]

To get your result, just use trivial string concatenation to join the 2nd and 3rd element from each result together.

UK Postcode, Regular Expression to Validate the format of a UK postcode. ln2 1ha GIR 0AA EC1A 1BB Hello, this is a postcode "ln21ha" standard 2nd class W1A 0AX M1  Geo::UK::Postcode::Regex::Simple may provide a more convenient way of using and customising these. regex, strict_regex, valid_regex Return regular expressions to parse postcodes and capture the constituent parts: area, district, sector and unit (or outcode, sector and unit in the case of valid_regex ).

I've used the excellent answer from @borodin above to create a UK postcode as-you-type formatter. Note, this does not validate the postcode, just formats it according to borodin's regex as the user types.

var txtPc = $("#postcode");
var outputCount = 0;
var jigCount = 0;
var postcodePauseTime = 500;

txtPc.on("keydown", function(e) {
  var keyCode = e.which;

  var key = String.fromCharCode(keyCode);
  var isAlphaNumeric = //key.match(/^[a-z0-9]+$/i);
      (keyCode >= 65 && keyCode <= 90) ||
      (keyCode >= 48 && keyCode <= 57) ||
      ([189, 190, 8, 46, 9].indexOf(keyCode) > -1) ||
      (keyCode >= 35 && keyCode <= 40)

  return !!isAlphaNumeric;
// handle click and add class
txtPc.on("keyup", function(e) {

txtPc.on("blur", function() {

function PostcodeCalculateFormat(txtPc) {
  (function(index, txtPc) {
    setTimeout(function() {
      //prevent interferance from other keypresses by returning out of this closure
      if (index != jigCount) return;
      var isFocused = ($('#' + txtPc.attr('id') + ':focus')[0] == document.activeElement);
      var postcodeText = txtPc.val().toUpperCase(); /// + key;
      var origSpacePos = postcodeText.indexOf(" ");
      postcodeText = postcodeText.replace(/[\W_]+/g, "");
      var parts = postcodeText.match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/i);
      //if unable to match the lot, try the first part only with less strict reg
      if (!parts)
        parts = postcodeText.match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(.*)$/i);
      if (parts) {
        var caretPos = 0;
        if (isFocused)
          caretPos = getCaretPosition(txtPc[0]).start;
        var newVal = parts.join(' ');
        if (newVal == txtPc.val())
        var spacePos = newVal.indexOf(" ");
        if (isFocused) {
          if (caretPos >= spacePos && origSpacePos == -1)

          setCaretPosition(txtPc[0], caretPos, caretPos);
    }, postcodePauseTime);
  }(++jigCount, txtPc));

function output(str) {
  $("#listOutput").prepend("<li>[" + (++outputCount) + "] " + str + "</li>");

function getCaretPosition(ctrl) {
  // IE < 9 Support
  if (document.selection) {
    var range = document.selection.createRange();
    var rangelen = range.text.length;
    range.moveStart('character', -ctrl.value.length);
    var start = range.text.length - rangelen;
    return {
      'start': start,
      'end': start + rangelen
  // IE >=9 and other browsers
  else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
    return {
      'start': ctrl.selectionStart,
      'end': ctrl.selectionEnd
  } else {
    return {
      'start': 0,
      'end': 0

function setCaretPosition(ctrl, start, end) {
  // IE >= 9 and other browsers
  if (ctrl.setSelectionRange) {
    ctrl.setSelectionRange(start, end);
  // IE < 9
  else if (ctrl.createTextRange) {
    var range = ctrl.createTextRange();
    range.moveEnd('character', end);
    range.moveStart('character', start);;
body {
  background: silver;
  padding: 20px;
  font-family: Helvetica;
<script src=""></script>

<div>Sample postcodes to type: 'BT92PE', 'EC1A3AD', 'GU348RR', 'N13LD'</div>

  Postcode: <input id="postcode" style="text-transform: uppercase; " />

<!-- for troubleshooting -->
<ul id="listOutput"></ul>

Regular Expressions, Format, Coverage, Example. Cell, Cell. AA9A 9AA, WC postcode area; EC1–EC4​, NW1W, SE1P, SW1, EC1A 1BB. A9A 9AA, E1W, N1C, N1P, W1A 0AX. In this java regex tutorial, we will Learn to use regular expressions to validate postal zip codes specific to UK. You can modify the regex to suit it for any other format as well. 1. What are valid UK postal codes Postal codes in the U.K. (or postcodes) are composed of five to seven alphanumeric

Advanced Search, This regular expression can be used to validate UK postcodes. whether the string specified is in the same format as the UK postcode format defined In the UK postal system not all letters are used in all positions (the same with  Check if a string only contains numbers pdf or jpg Match string not containing string Green Core Serial UnsignedWithoutU Match dates (M/D/YY, M/D/YYY, MM/DD/YY, MM/DD/YYYY) URLquery string adjuster Match IDs uk postcodes Match a bitcoin address Kod pocztowy validateFilename Match an MD5 hash HCL_HCRG_ASHX_CROSSDOMAIN mau

Details, Regular expression to match valid UK postcodes. In the UK postal system not all letters are used in all positions (the same with vehicle registration plates) and there are various rules to The correct matching string for a UK address is; (GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?) How can I convert it to check postcodes in a rule​? I'd advise anyone arriving here from search engines to avoid the regex in the above comment (it's perhaps typical that the UK government would be using a badly formed regex) because it doesn't match a lot of valid postcodes (e.g. W1T 1PG), and it's inconsistent in that it matches some postcodes with a space and some without.

Postcode Validation with Regex - JavaScript, I found online which use regex to validate and format UK postcodes. I really There is a list of allowed postcodes stored with a variable or array. tests to see if string is in correct UK style postcode: AL1 1AB, BM1 5YZ etc. Regular expression to match valid UK postcodes. In the UK postal system not all letters are used in all positions (the same with vehicle registration plates) and there are various rules to govern this. This regex takes into account those rules.

  • what do you exactly mean with "how to use the regex as a mask" ?
  • I would like to be able to convert the string to match the regex. E.G. if I have a regex to validate a string matches, I would like to be able to format a string accordingly (primarily in this case to insert a space in the relevant part of the postcode)
  • This made it idiot proof and worked with no need to think. Thanks to both.
  • @PaulChopsHelyer you're not supposed to avoid thinking, that's why I didn't spoon feed you a whole function.
  • Thank you Alnitak, however my "not thinking" comment may have been a little flippant and taken wrongly. A functional example allows me to see and learn at the same time. Apologies if you feel this is not the way to do it, but having spent a few fruitless hours trying to piece together something from various examples that I did not understand, this has now led me to be able to adapt Borodin's example to suit my requirements. Thank you again for your help, it really is appreciated.
  • Great answer & simple, straight forward solution. I've used your logic above in my much messier answer below with credit to you. Thanks
  • Thanks Alnitak, So what syntax would I use to get a string of "N1 3LD" from "N13LD" from your example?
  • @PaulChopsHelyer just take the 2nd and 3rd elements from the result of .match().
  • @Alnitak: It may massage your ego to think that I plagiarised your solution, but believe me that is not the case. There are only so many ways to write such a regular expression and mine is about as different from yours as it could be while doing a very similar thing. Venting your frustration at both me and the OP will bring you neither admiration nor reputation points.
  • @Borodin fair enough, but it rather looked that way from here seeing as you also corrected the OP's mistake but didn't mention that you had done so.
  • @Alnitak: if you look at the edit history you will see that I haven't changed the OP's question either.