5

I have java Regex pattern for UK Postcode:

^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$

I want to use it in Javascript as well but it does not validate Postcodes correctly in Javascript. Is there any difference between Regex patterns in Java and Javascript?

2
  • What is the format of UK's postal code, give us the pattern that you would like to search? Commented Apr 21, 2016 at 16:31
  • It works in js for "DE56 2SR". What postal code do you have that it is not working with? Commented Apr 21, 2016 at 16:39

2 Answers 2

7

There is a difference between Java and JavaScript regex flavors: JS does not support lookbehind.

A tabulation of differences between regex flavors can be found on Wikipedia.

However, this does not apply to your case. I surmise that your JS test string has spurious characters, eg. cr/lf.

Try to use the regex without the anchors and check the lengths of the test strings.

Sign up to request clarification or add additional context in comments.

Comments

-1

Your regex works just as well in JavaScript as Java. Below is a short example using some data I made up.

var regex = /^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$/;

var testData = [

  // valid
  'A11 1AA',
  'a1 1aa',
  'Aa1a 1AA',
  'aA11 1aa',
  'Aa1 1AA',

  // invalid
  'aa1aa 1aa',
  '@a11 1aa',
  'a1aa 1aa'
];

for (var i = 0; i < testData.length; i++) {
  if (testData[i].match(regex)) {
    console.log(testData[i] + ' is valid.');
  } else {
    console.log(testData[i] + ' is invalid.');
  }
}

Bonus tips:

You could simplify your regex some. The {1} is unnecessary, and you don't need to wrap the space in [].

 ^[a-zA-Z]([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]) [0-9][a-zA-z][a-zA-z]$

Of course, you can leave in any () that you want for capture groups, but I don't know if you are using those.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.