Python Regex Match

August 9, 2017
Use re.search

Assuming you want determine if a string match a certain pattern, re.search is your best bet. You might think of using re.match, but the use case is more specific as it match the beginning of the string (or the whole string).

import re

url = "https://www.luasoftware.com/tutorials/python/python-regex-match.html"

# regex for begins with
m = re.search(r"^https://", url)
if m:
  print("is https")

# regex for middle match
m = re.search(r"://([\w\d-]+\.)?luasoftware.com/", url)
if m:
  print("domain is luasoftware.com")

# regex for ends with
m = re.search(r"\.html$", url)
if m:
  print("file extension is html")
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.