Home > Software design >  Regex to accept numbers with spaces
Regex to accept numbers with spaces

Time:08-10

We have a expression to accept regex with spaces but the pattern should match below examples

ABC1234   
TAC4 566    
T A C 4 5 6 6    
KA C4 56 6

Basically all spaces should be accepted with 3 alpha characters[A-z] and followed by 4 numbers[0-9]

I tried using this regex but it doesnt work :

^((\s)*([a-zA-Z]{3})([0-9]{4}))?$

CodePudding user response:

Assuming no trailing/leading psaces (as per given sample data), the very verbose version could be:

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

See an online demo. It basically means the same as ^[A-Z] ?[A-Z] ?[A-Z] ?\d ?\d ?\d ?\d$ where:

  • ^ - Match start-line anchor;
  • [A-Z] - An uppercase alpha;
  • (?: ?[A-Z]){2} - Non-capture group to match an optional space and an uppercase alpha twice;
  • ?\d - Optional space and single digit;
  • (?: ?\d){3} - Non-capture group to match an optional space and a digit three times;
  • $ - End-line anchor.

CodePudding user response:

Put \s* after the pattern for letter or number to allow any amount of spaces after that character. Put these in groups so you can then quantify them to allow 3 letters followed by 4 numbers.

^\s*([a-zA-Z]\s*){3}(\d\s*){4}$

CodePudding user response:

/[A-Za-z]\s?[A-Za-z]\s?[A-Za-z]\s?\d\s?\d\s?\d\s?\d/g it's big and inelegant but it'll meet your criteria.

Regex101

  • Related