0

What is the issue here

This is regarding python regex, (Course: Python->Regular Expression->Module 5) (or (|) concept) In the following example, import re pattern = r"gr(a|e)y" match = re.match(pattern, "gray") if match: print ("Match 1") # Output match = re.match(pattern, "grey") if match: print ("Match 2") # Output match = re.match(pattern, "graey") if match: print ("Match 3") Now when I remove the 'y', import re pattern = r"gr(a|e)" match = re.match(pattern, "gra") if match: print("Match 1") # Output match = re.match(pattern, "gre") if match: print("Match 2") # Output match = re.match(pattern, "grae") if match: print("Match 3") # Output then "Why does the 3rd case match?"

23rd Oct 2020, 10:53 AM
Arun Bhattacharya
Arun Bhattacharya - avatar
4 ответов
+ 2
The pattern says That it should start with "gr" then a or e grae matches with this condition It doesn't matter what it has after gra or gre The same with r"gr(a|e)y" pattern it Only wants gray or grey and doesn't care of anything after that It will also match greyish and grayish Hope It Helps You 😊
23rd Oct 2020, 11:10 AM
Hacker Badshah
Hacker Badshah - avatar
+ 7
if you like you can check the match visually with pythex.org: https://pythex.org/?regex=gr(a%7Ce)&test_string=grae&ignorecase=0&multiline=0&dotall=0&verbose=0
23rd Oct 2020, 11:10 AM
Lothar
Lothar - avatar
+ 2
gr(a|e) pattern matches any string starting with "g" ,followed by "r" and then followed by "a" or "e" ,"in grae" it matches "gra" gr(a|e)y matches string "gr" followed by either one "a" or "e" and then immediately by "y" ,that's why it doesn't gives a match for "greay" since there are two characters("e" and "a") after "gr" if you want the first pattern to match two characters before "y" you can use gr(a|e)*y now it will match "gr" and then two or more than two "a" or "e" and then check for "y" ,"*" means one or more appearance of a particular character
23rd Oct 2020, 11:06 AM
Abhay
Abhay - avatar
+ 1
Thanks Everyone
24th Oct 2020, 12:11 PM
Arun Bhattacharya
Arun Bhattacharya - avatar