Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enforce that certain characters must be present when there is an optional character before them?

I would like to capture a string that meets the criteria:

  1. may be empty

  2. if it is not empty it must have up to three digits (-> \d{1,3})

  3. may be optionally followed by a uppercase letter ([A-Z]?)
  4. may be optionally followed by a forward slash (i.e. /) (-> \/?); if it is followed by a forward slash it must have from one to three digits (-> \d{1,3})

Here's a valid input:

  • 35
  • 35A
  • 35A/44

Here's invalid input:

  • 34/ (note the lack of a digit after '/')

I've come up with the following ^\d{0,3}[A-Z]{0,1}/?[1,3]?$ that satisfies conditions 1-3. How do I deal with 4 condition? My Regex fails at two occassions:

  • fails to match when there is a digit and a forward slash and a digit e.g .77A/7
  • matches but it shouldn't when there isa digit and a forward slash, e.g. 77/
like image 703
menteith Avatar asked Dec 14 '25 05:12

menteith


1 Answers

You may use

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

See the regex demo

Details

  • ^ - start of string
  • (?:\d{1,3}[A-Z]?(?:\/\d{1,3})?)? - an optional non-capturing group:
    • \d{1,3} - one to three digits
    • [A-Z]? - an optional uppercase ASCII letter
    • (?:\/\d{1,3})? - an optional non-capturing group:
      • \/ - a / char
      • \d{1,3} - 1 to 3 digits
  • $ - end of string.

Visual graph (generated here):

enter image description here

like image 82
Wiktor Stribiżew Avatar answered Dec 16 '25 19:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!