Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for 5 digit number with optional characters

Tags:

regex

I am trying to create a regex to validate a field where the user can enter a 5 digit number with the option of adding a / followed by 3 letters. I have tried quite a few variations of the following code:

^(\d{5})+?([/]+[A-Z]{1,3})? 

But I just can't seem to get what I want.

For instance l would like the user to either enter a 5 digit number such as 12345 with the option of adding a forward slash followed by any 3 letters such as 12345/WFE.

like image 420
Callum A Macleod Avatar asked Sep 29 '13 15:09

Callum A Macleod


People also ask

What does \f mean in regex?

\f stands for form feed, which is a special character used to instruct the printer to start a new page. [*\f]+ Then means any sequence entirely composed of * and form feed, arbitrarily long.

How do you represent digits in regex?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).

How does regex Match 5 digits?

match(/(\d{5})/g);


1 Answers

You probably want:

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

You might have to escape that forward slash depending on your regex flavor.

Explanation:

  • ^ - start of string anchor
  • \d{5} - 5 digits
  • (?:/[A-Z]{3}) - non-capturing group consisting of a literal / followed by 3 uppercase letters (depending on your needs you could consider making this a capturing group by removing the ?:).
  • ? - 0 or 1 of what precedes (in this case that's the non-capturing group directly above).
  • $ - end of string anchor

All in all, the regex looks like this:

enter image description here

like image 164
arshajii Avatar answered Oct 16 '22 08:10

arshajii