Regex to validate an alphanumeric string with optional space

Viewed 600

I have been working on a regex for validating an alphanumeric string with the rules as below:

  1. The first FOUR starting characters must be numbers and last TWO characters must be alphabets.

  2. The space is OPTIONAL but must be placed between two characters, meaning trailing space is not allowed.

  3. The length of postal code must be 6 characters if SPACE is not included and 7 characters if space is included.

Eg.

  • 1111 ZZ
  • 111 1ZZ
  • 1 111ZZ
  • 1111ZZ

I tried using ^[0-9]{4}[A-Za-z]{2}$|^(?=[\d|\D]+ [\d|\D]+).{7}$ but this also validates 9999 1A as TRUE which should actually be FALSE.

Any leads or help will be appreciated :)

3 Answers

I suggest simplifying the problem ahead of time, by reducing all white spaces, which you seem to be uninterested in anyway:

var candidate = input.replaceAll(/\s/mg, '');

Then the regex is simply: /^\d{4}[A-Za-z]{2}$/

If, however, you need to validate, that there actually are no leading or trailing white spaces, you can validate that ahead of time, and return a negative result right away.

(?=^.{6,7}$)^(([0-9] ?){4}( ?[a-zA-Z]){2})$

will match

  • 1111 ZZ
  • 111 1ZZ
  • 1 111ZZ
  • 1111ZZ
  • 1111 ZZ

but not

  • 9999 1A
  • 11111 Z
  • 1111111
  • 11 11 ZZ

https://regex101.com/r/lByOx6/1

EDIT: explanation

The "Positive Lookahead" part:

  • (?=^.{6,7}$) this only matches if the string meets the requirements, BUT it does not 'consume' the characters.
    • . is any character
    • {6,7} is about repetitions

so (?=^.{6,7}$) is matched if the string has 6 or 7 characters, no matter what

Then the following part already 'consumes' the string to say that I want at the start 4 repetitions of numbers and optionally space, and at the end 2 repetitions of letters and optionally space. The second part would accept strings such as 1 1 1 1 Z Z but as those are more than 7 characters, the first part wouldn't let the string match.

Another option is to check if the string contains an optional space between the first and the last non whitespace character.

Then match the first digit followed by 3 digits separated by an optional space and 2 or 3 times a char a-zA-Z or a space.

Using a case insensitive match:

^(?=\S+ ?\S+$)\d(?: ?\d){3}[A-Z ]{2,3}$

Explanation

  • ^ Start of string
  • (?= Positive lookahead, assert what on the right is
    • \S+ ?\S+$ Match optional space between the first and the last non whitespace char
  • ) Close lookahead
  • \d(?: ?\d){3} Match a digit and repeat 3 times an optional space and a digit
  • [a-zA-Z ]{2,3} Match 2-3 times either a char a-zA-Z or a space
  • $ End of string

Regex demo

Related