Timotej Leginus
Timotej Leginus

Reputation: 294

Regex for matching a pattern which only needs to start with a valid sequence start

I have this regex pattern here /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/. It's for validating HH:MM 24-hour strings with optional leading zero.

However, when I match this against the string 23:59, for example, it works. That's a good thing. But I would like to also match these strings: 2, 23, 23:, 23:5 and 23:59. After hours and hours of debugging, I still couldn't look for something like this, if it exists.

(If it's useful, I'm using the Objective-C regex engine, or optionally I can use the Swift one as well.)

Upvotes: 0

Views: 55

Answers (2)

The fourth bird
The fourth bird

Reputation: 163362

You could start the match with a digit 00-23 or and make the all the minute parts optional.

^(?:[01]?[0-9]|2[0-3])(?::(?:[0-5][0-9]?)?)?$

Explanation

  • ^ Start of string
  • (?: Non capture group
    • [01]?[0-9] Match from 00 - 19 or 0-9
    • | Or
    • 2[0-3] match 20-23
  • ) Close group
  • (?: Non capture group
    • : Match a : char
    • (?:[0-5][0-9]?)? Optionally match 5 and an optional digit 0-9
  • )? Close group and make it optional
  • $ End of string

Regex demo

Upvotes: 2

JvdV
JvdV

Reputation: 75870

Looks like the following could work:

^(?:[01]?[0-9]|2[0-3])(?::(?:[0-5]?[0-9])?)?$

See the online demo

  • ^ - Start string anchor.
  • (?: - Open 1st non-capture group:
    • [01]? - Optional zero or one;
    • [0-9] - Any digit;
    • | - Or:
    • 2[0-3] - A two followed by a numer ranging from zero to three;
    • ) - Close 1st non-capture group.
  • (?: - Open 2nd non-capture group:
    • : - A colon;
    • (?: - Open 3rd non-capture group:
      • [0-5]?[0-9] - Optional number from zero to five and a number from zero to nine;
      • )? - Close 3rd non-capture group and make it optional.
    • )? - Close 2nd non-capture group and make it optional.
  • $ - End string anchor.

Upvotes: 2

Related Questions