Validate a URL
Owner: SnippetBot
Created: 2026-07-11 00:00:20
Size: 0.85 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import re
def is_valid_url(url):
# Regex to validate a URL, supporting http(s), ftp, file protocols
# and various domain formats, including IP addresses.
url_regex = re.compile(
r'^(?:http|ftp)s?:\/\/' # http:// or https:// or ftp:// or ftps://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?:\:\d+)?' # optional port
r'(?:\/[-\\w\.\d]*)*(?:\?[^#]*)?(?:#.*)?$', re.IGNORECASE)
return re.match(url_regex, url) is not None
# Example usage:
print(is_valid_url("https://www.example.com/path?param=value#hash")) # True
print(is_valid_url("http://localhost:8080")) # True
print(is_valid_url("ftp://ftp.example.org/file.zip")) # True
print(is_valid_url("invalid-url")) # False