menteith
menteith

Reputation: 678

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:

Here's invalid input:

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:

Upvotes: 3

Views: 52

Answers (2)

Feathercrown
Feathercrown

Reputation: 2591

This should work. You were matching an optional slash and then an optional digit from 1 to 3; this matches an optional combination of a slash and 1-3 of any digits. Also, your original regex could match 0 digits at the beginning; I believe that this was in error, so I fixed that.

var regex = /^(\d{1,3}[A-Z]{0,1}(\/\d{1,3})?)?$/g;

console.log("77A/7 - "+!!("77A/7").match(regex));
console.log("77/ - "+!!("77/").match(regex));
console.log("35 - "+!!("35").match(regex));
console.log("35A - "+!!("35A").match(regex));
console.log("35A/44 - "+!!("35A/44").match(regex));
console.log("35/44 - "+!!("35/44").match(regex));
console.log("34/ - "+!!("34/").match(regex));
console.log("A/3 - "+!!("A/3").match(regex));
console.log("[No string] - "+!!("").match(regex));

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627580

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

Upvotes: 3

Related Questions