Regular Expression for any number divisible by 60 using C# .Net?

前端 未结 6 1398
梦谈多话
梦谈多话 2021-01-18 10:32

I need to apply validation on input time intervals that are taken in as seconds. Now i am not really good at Regular expressions. So can any body help making a regular expre

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-18 10:53

    As others have mentioned, regular expressions are completely the wrong tool to use for this. Rather, use TryParse to convert the string to an integer, and then test whether the integer is divisible by 60.

    That said, it is instructive to see how this could possibly work with a regexp.

    First off, of the one-digit numbers, only 0 is evenly divisible by 60. Of the non-one-digit numbers, all numbers divisible by 60 are also divisible by 20, and therefore end in 00, 20, 40, 60 or 80. That is easily tested with a regexp.

    Suppose it passes the first test. We know from this test that the number is divisible by 20. Now all we need to do is show that it is divisible by 3. If it is, then it is divisible by both 20 and 3 and therefore must be divisible by 60, since 20 and 3 are coprime.

    So we need a regular expression that can determine if a number is divisible by 3.

    It is well known that numbers divisible by three are such that the sum of their digits is divisible by 3.

    It is also well known that every regular expression corresponds to a finite state machine, and every finite state machine corresponds to a regular expression.

    Therefore if we can come up with a finite state machine that determines divisibility by three, we're done.

    This is easily done. Our finite state machine has three states, A, B and C. The start state is A. The accepting state is A. The transitions are:

    When in state A, inputs 0, 3, 6 and 9 go to state A. Inputs 1, 4 and 7 go to state B. Inputs 2, 5 and 8 go to state C.

    When in state B, inputs 0, 3, 6 and 9 go to state B. Inputs 1, 4 and 7 go to state C. Inputs 2, 5 and 8 go to state A.

    When in state C, inputs 0, 3, 6 and 9 go to state C. Inputs 1, 4 and 7 go to state A. Inputs 2, 5 and 8 go to state B.

    All other inputs go to an error state.

    And we're done; we have a finite state machine that checks for divisibility by 3. Therefore we can build a regexp that checks for divisibility by 3; if we combine that with the regexp that checks for divisibility by 20, then we have the desired regular expression. The language of numbers written in decimal notation divisible by 60 is a regular language.

    The actual construction of such a regular expression is left as an exercise. (Looks like that's what tiftik has done.)

    Exercise: can you come up with a regular expression that determines if string contains a decimal number that is evenly divisible by 70? If you can, let's see it. If not, can you provide a proof that no such regular expression exists? (That is, that the language I am describing is not regular.)

提交回复
热议问题