Regex to allow user to enter time - C #

Many other questions provide answers to regular expression expressions that allow fully completed times, such as this : ^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$

But this is useless in the Textbox.TextChanged event, because when you enter 15:45 text field will contain 15: which does not match the expression above.

Is there an easy way to allow a partial match of a Regex expression to ensure that the half-cycle time passes anyway, or do I have to split the expression into parts of it, all highlighted by or s, for example this ?

+5
source share
1 answer

You can manually adjust such patterns to allow partial matches. One thing to keep in mind is that they are only good for real-time verification, not final verification. To complete the final check, you need to use the full template without any additional parts (or only these required additional parts).

So this technique is to use nested optional non-capturing groups like (?:...(?:...)?)? .

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

Watch the regex demo

More details

  • ^ - start of line
  • (?: - start an optional group without capture
    • (?: - start an optional group without capture
      • [01]?[0-9] - optional 0 or 1 , and then any 1-digit
      • | - or
      • 2[0-3] - 2 , and then a digit from 0 to 3
    • ) - end of optional group not performing capture
  • (?: - start an optional group without capture
    • : - colon
    • (?: - start an optional group without capture
      • [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
  • $ is the end of the line.
+3
source

Source: https://habr.com/ru/post/1269997/


All Articles