-3

I have this question where I need to determine if a number is divisible by 7 using only REGEX in python.

This is what I came up with:
0 7 14 21 ... 91 98 The numbers that appear are: 0-9 for the first and second

and all the trailing left digits can appear as many as they want so \d*

the regex is: \d*\d\d - did the opposite, it returned true for numbers that were not divisible by 7

for example re.match(theReg, '32780') returned False and I need it to return True, so I negated the whole regex to the very final:

~\d*\d\d    

This SOMEHOW works for all the numbers, but again, the opposite, it returns False for numbers that are divisible by 7...

Another question: I did not seem to find any way to negate a regex, so how the hell does ~ do all the work?

Thanks!

CodeCop
  • 1
  • 2
  • 15
  • 37
  • 2
    That regex makes no sense. It says "any number of digits, followed by a digit, followed by another digit". That matches any sequence of 2 or more digits. You didn't do anything to require any sort of relationship between the digits. – user2357112 Apr 27 '20 at 00:55
  • Also `~` isn't a negation operator. It's just a tilde. – user2357112 Apr 27 '20 at 00:56
  • @user2357112supportsMonica how do you explain that all the numbers that are not divisible by 7 return true and the numbers that are return false? – CodeCop Apr 27 '20 at 01:06
  • 2
    I explain that by pointing out that you're wrong. Divisibility by 7 has no effect whatsoever on whether or not any of these regexes match. – user2357112 Apr 27 '20 at 01:14
  • Can you clarify your question? Please see [ask], [help/on-topic]. – AMC Apr 27 '20 at 02:14

2 Answers2

0

Your program checks if the answer from re.match(reg, strn) the same as what you need\want it to be - a number divisible by 7 (so you are checking if the output is equal to the number % 7).

This is where you get things wrong, your final Regex returns None for any string containing numbers - and so of course it will "get right" all the strings that contain numbers that are not divisible by 7, in fact it will get anything you wish the answer to be is Falsy!

0

Making a REGEX that could determine if a number is a multiple of 7 definitely exists, but it is probably very complicated and nasty. Check out the discussion here (Check number divisibility with regular expressions) for more info.

As for the regex ~\d*\d\d it would match any string that starts with ~ and have at least 2 digits. I'm not exactly sure the logic of this string.

Garrigan Stafford
  • 1,331
  • 9
  • 20