pattern = r"^gr.y$"
if re.match(pattern, "grey"):
print('Match1') #Match1
if re.match(pattern, "greeey"):
print('Match2') #Don't match
if re.match(pattern, "greeeeeeeeey"):
print('Match3') #Don't match
Above is my code, but I want every string that starts with "gr" and ends with "y" satisfy the condition. I wonder if there and or condition in regex? Maybe satisfy condition 1 and condition 2, condition 1 or condition 2, startwith 1 and endwith 2?
>Solution :
You don’t need regex for that:
text = "grey"
if text.startswith("gr") and text.endswith("y"):
print("Match")
If you want to use regex anyway:
import re
text = "grey"
if re.match(r"^gr.*y$", text):
print("Match")
*will repeat the preceding token (.) between zero and unlimited times, as much as possible (greedy).