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