google drive url regex in python

To validate a Google Drive URL using regex in Python, you can use the following pattern:

main.py
import re

pattern = r'^https://drive\.google\.com/(file/d/\w+|open\?id=\w+)$'

url = 'https://drive.google.com/file/d/1zHj2MaefJaCzsrDxBs7HvmGpAE9xiTCh/view'
match = re.match(pattern, url)

if match:
    print('Valid Google Drive URL')
else:
    print('Invalid Google Drive URL')
281 chars
12 lines

This pattern matches two possible URL formats:

  • https://drive.google.com/file/d/<file_id>
  • https://drive.google.com/open?id=<file_id>

where <file_id> is a sequence of word characters (letters, digits, or underscores).

Note that this pattern does not verify whether the file exists or if the user has access to it. It simply checks if the URL is in a valid Google Drive format.

gistlibby LogSnag