0

Regex {} question

Looking at this code https://code.sololearn.com/433/#py I don't understand, why changing line 3 to r"9{0,3}

quot; will not match "8" Since it's between 0 and 3 and "8" has zero "9" then it should match, right? What am I missing?

19th Sep 2020, 6:11 AM
Nassim Abed
Nassim Abed - avatar
7 ответов
+ 1
Nassim Abed don't you think an empty string will match 0 9's. You can also check by doing the below. import re pattern = r"89{0,3}
quot; if re.match(pattern, "8"): print("Match 1") if re.match(pattern, "899"): print("Match 2") if re.match(pattern, "8999"): print("Match 3")
19th Sep 2020, 8:18 AM
Avinesh
Avinesh - avatar
0
Your regex is explicitly looking for the number 9. Any other character will not match. Zero 9 is not 8
19th Sep 2020, 6:42 AM
CHMD
CHMD - avatar
0
How could you match 8 when the pattern is to just match 0 to 3 nines in the string.
19th Sep 2020, 6:43 AM
Avinesh
Avinesh - avatar
0
Ok then what exactly will match zero 9's?
19th Sep 2020, 7:05 AM
Nassim Abed
Nassim Abed - avatar
0
Use a range [1-8]{1,3} This will match any number between 1 and 8. You can change the range ( ex: change 1 to 0 to match numbers from 0 to 8) and the quantifiers to fit your needs.
19th Sep 2020, 7:11 AM
CHMD
CHMD - avatar
0
Thanks for the workaround. Workarounds aside, what is the syntax for matching zero repetitions? I am struggling to understand how Python deals with the logic of it. It seems so far that null is not zero, which is clear enough, but still doesn't answer the question: how to modify this code, what will match zero 9's without changing r"9{0,3}
quot;??
19th Sep 2020, 7:19 AM
Nassim Abed
Nassim Abed - avatar
0
:) Thank you Avinesh.
19th Sep 2020, 9:16 AM
Nassim Abed
Nassim Abed - avatar