Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to allow a user to type in a time - C#

Tags:

c#

regex

textbox

Lots of other questions give answers for regex expressions which only allow fully completed times like this: ^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$

But this is no use in a Textbox.TextChanged event because while typing 15:45 the textbox will contain 15: which doesn't match the expression above.

Is there an easy way to allow a partial match of a Regex expression to ensure a half typed time still passes or would I have to break the expression down into its parts all separated out by ors, like this?

like image 800
Toby Smith Avatar asked Oct 18 '22 08:10

Toby Smith


1 Answers

You may manually adjust such patterns to allow partial matches. One thing to remember is that they are only good for live validation, not final validation. To perform final validation, you need to use a complete pattern with no optional parts (or just those obligatory optional parts).

So, the technique consists in using nested optional non-capturing groups, like (?:...(?:...)?)?.

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

See the regex demo

Details:

  • ^ - start of string
  • (?: - start of an optional non-capturing group
    • (?: - start of an optional non-capturing group
      • [01]?[0-9] - an optional 0 or 1 and then any 1 digit
      • | - or
      • 2[0-3] - 2 and then a digit from 0 to 3
    • ) - end of an optional non-capturing group
  • (?: - start of an optional non-capturing group
    • : - a colon
    • (?: - start of an optional non-capturing group
      • [0-5][0-9]? - a digit from 0 to 5 and then any optional digit
    • )? - end of an optional non-capturing group
    • )? - end of an optional non-capturing group
  • )? - end of an optional non-capturing group
  • $ - end of string.
like image 88
Wiktor Stribiżew Avatar answered Oct 23 '22 03:10

Wiktor Stribiżew