Home > Blockchain >  Regex for 5-7 characters, or 6-8 if including a space (no special characters allowed)
Regex for 5-7 characters, or 6-8 if including a space (no special characters allowed)

Time:02-17

I am trying to create a regex for some basic postcode validation. It doesn't need to provide full validation (in my usage it's fine to miss out the space, for example), but it does need to check for the number of characters being used, and also make sure there are no special characters other than spaces.

This is what I have so far:

^[\s.]*([^\s.][\s.]*){5,7}$

This mostly works, but it has two flaws:

  1. It allows for ANY character, rather than just alphanumeric characters spaces
  2. It allows for multiple spaces to be inserted:

I have tried updating it as follows:

^[\s.]*([a-zA-Z0-9\s.][\s.]*){5,7}$

This seems to have fixed the character issue, but still allows multiple spaces to be inserted. For example, this should be allowed:

AB14 4BA

But this shouldn't:

AB1 4 4BA

How can I modify the code to limit the number of spaces to a maximum of one (it's fine to have none at all)?

CodePudding user response:

With your current set of rules you could say:

^(?:[A-Za-z0-9]{5,7}|(?=.{6,8}$)[A-Za-z0-9] \s[A-Za-z0-9] )$

See an online demo


  • ^ - Start-line anchor;
  • (?: - Open non-capture group for alternations;
    • [A-Za-z0-9]{5,7} - Just match 5-7 alphanumeric chars;
    • | - Or;
    • (?=.{6,8}$) - Positive lookahead to assert position is followed by at least 6-8 characters until the end-line anchor;
    • [A-Za-z0-9] \s[A-Za-z0-9] - Match 1 alphanumeric chars on either side of the whitespace character;
    • )$ - Close non-capture group and match the end-line anchor.

Alternatively, maybe a negative lookahead to prevent multiple spaces to occur (or at the start):

^(?!\S*\s\S*\s|\s)(?:\s?[A-Za-z0-9]){5,7}$

See an online demo where I replaced \s with [^\S\n] for demonstration purposes. Also, though being the shorter expression, the latter will take more steps to evaluate the input.

  • Related