Callum A Macleod
Callum A Macleod

Reputation: 165

Regex for 5 digit number with optional characters

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.

Upvotes: 6

Views: 3646

Answers (4)

arshajii
arshajii

Reputation: 129497

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

Upvotes: 9

Quine
Quine

Reputation: 158

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

Tested in rubular

Upvotes: 2

Levi
Levi

Reputation: 2113

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

Here it is in practice (this is a great site to test your regexes): http://regexr.com?36h9m

Upvotes: 2

anubhava
anubhava

Reputation: 784998

You can use this regex

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

Upvotes: 2

Related Questions