Check number divisibility with regular expressions

前端 未结 6 2175
我寻月下人不归
我寻月下人不归 2020-12-05 18:39

Given a decimal number N as a string of digits, how do I check if it\'s divisible by M using regular expressions only, without con

6条回答
  •  没有蜡笔的小新
    2020-12-05 19:35

    As interesting as this question is, I don't believe it's possible for anything other than the "obvious" ones you list.

    Most of the divisibility rules require mathematical manipulation.


    You could use a lookahead to test the string for more than one requirement, so that you can combine pairs of the "obvious" ones together (2 x 3, 3 x 5, etc.):

    Matching a 6-letter word is easy with \b\w{6}\b. Matching a word containing "cat" is equally easy: \b\w*cat\w*\b.

    Combining the two, we get: (?=\b\w{6}\b)\b\w*cat\w*\b Analyze this regular expression with RegexBuddy. Easy! Here's how this works. At each character position in the string where the regex is attempted, the engine will first attempt the regex inside the positive lookahead. This sub-regex, and therefore the lookahead, matches only when the current character position in the string is at the start of a 6-letter word in the string. If not, the lookahead will fail, and the engine will continue trying the regex from the start at the next character position in the string.

提交回复
热议问题