Optimistic RegEx compliance for user text input

I am working on a text application that uses regular expressions to validate user input. The goal is to allow keystrokes that match a specific RegEx and to reject invalid characters. One of the problems that I encountered is that when the user starts to enter information, he can create a string that does not match the given regular expression yet, but may lead to a match in the future. These lines are erroneously rejected. Here's an example - the following regular expression is set to enter date information:

(0?[1-9]|10|11|12)/(0?[1-9]|[12]\\d|30|31)/\\d{2}\\d{2}

The user can start typing "1 /", which may be a valid date, but RegEx.IsMatch()will return false, and my code will finish rejecting the line. Is there a way to โ€œoptimisticallyโ€ test strings against a regular expression to allow possible or partial matches?

Bonus: for this RegEx, in particular, there are some sequences that cause the required characters. For example, if the user enters โ€œ2/15,โ€ the only valid character that they can enter further is โ€œ/โ€. Can these scenarios be detected so that the necessary characters can be automatically entered for the user to facilitate input?

+3
source share
2 answers

, RegExp (.. ^ $, / ) optionnal , , . - :

^(0?[1-9]|10|11|12)(/((0?[1-9]|[12]\\d|30|31)(/(\\d{2}(\\d{2})?)?)?)?)?$

, , , , regexp , regexp.

, , , - // .
  , , , , .

+2

- , , , ? "", , ?

, , , , . , , , .

, , . , , , .

+1

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


All Articles