python-regexHow to match a URL using Python regex?
Python regex can be used to match a URL. The following example code block uses the re.search()
function to match a URL:
import re
url = 'https://www.example.com/path/to/page'
match = re.search(r'https?://(www\.)?\w+\.\w+/\S+', url)
if match:
print(match.group())
The output of the example code is:
https://www.example.com/path/to/page
Code explanation
import re
: imports there
module which provides regular expression matching operations.url = 'https://www.example.com/path/to/page'
: assigns the URL to a variable.re.search(r'https?://(www\.)?\w+\.\w+/\S+', url)
: searches for a match of the regular expression pattern in the URL. The pattern consists of the following parts:https?://
: matcheshttp
orhttps
at the beginning of the URL.(www\.)?
: matcheswww.
at the beginning of the URL, if present.\w+\.\w+
: matches the domain name./\S+
: matches the path of the URL.
if match:
: checks if a match was found.print(match.group())
: prints the matched URL.
Helpful links
More of Python Regex
- How to replace all using Python regex?
- How to use word boundaries in Python Regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a year with Python Regex?
- How to match whitespace in Python regex?
- How to match a UUID using Python regex?
- How to ignore case in Python regex?
- How to remove numbers from a string using Python regex?
- How to replace a certain group using Python regex?
- How to match a URL path using Python regex?
See more codes...