Can anyone say why the output differs in the following 2 codes ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone say why the output differs in the following 2 codes ?

----------------- Code #1 : ----------------- import re pattern = r"(.*) \1" match = re.match(pattern, "word word") if match: print ("Match 1") match = re.match(pattern, "?! ?!") if match: print ("Match 2") match = re.match(pattern, "abc cde") if match: print ("Match 3") ------------------- Code #2 : ------------------- import re pattern = r"(.*)" match = re.match(pattern, "word word") if match: print ("Match 1") match = re.match(pattern, "?! ?!") if match: print ("Match 2") match = re.match(pattern, "abc cde") if match: print ("Match 3") The first code gives the output... Match 1 Match 2 Whereas the second code gives the output... Match 1 Match 2 Match 3 Why ?

4th Apr 2020, 3:16 PM
Kiran Deep Naidu
Kiran Deep Naidu - avatar
1 Answer
+ 2
The pattern "(.*) \1" means that it needs to match the group (.*) (which is any number of anything) but it then has to be followed by a space (as there is a space in the pattern) and then the same group again (which the '\1' requires). The third string is "abc cde" but because it's not the same two things separated by a space, it does not match.
4th Apr 2020, 3:24 PM
Russ
Russ - avatar