Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to match a string start and end with a character, don't care about the length of the string (using regex python)?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading