Why the "Match2" can't be printed with the pattern r"(\D+\d)"? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why the "Match2" can't be printed with the pattern r"(\D+\d)"?

import re pattern = r"(\D+\d)" match = re.match(pattern, "1, 23, 456!") if match: print("Match 2") Why the "Match2" can't be printed with the pattern r"(\D+\d)"? I thought there would be two sub-string that can be matched, ", 2" and ", 4"

18th Nov 2017, 1:47 PM
Kevin Yang
Kevin Yang - avatar
3 Answers
+ 6
The pattern r"(\D+\d)" matches only a string which starts with non-digit and then has a digit. When you are use re.match it looks in the beggining of a string to find that pattern. "1, 23, 456!" starts with a digit (1) and that's why it doesn't match the pattern. But if you use re.search instead it will be a match.
18th Nov 2017, 2:18 PM
Tim Thuma
Tim Thuma - avatar
+ 5
Try using re.findall instead of re.match
18th Nov 2017, 2:16 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
@Tim @Kuba Thank you.I see. I forget that the "re.match" is just applied at the beginning of a string.
19th Nov 2017, 1:49 PM
Kevin Yang
Kevin Yang - avatar