Regex Pattern for URL Matching
Matching URLs reliably requires handling protocols, domains, ports, paths, query parameters, and fragments. This example pattern captures the essential structure of an HTTP or HTTPS URL without being overly strict. Test it against absolute URLs, relative paths, and edge cases like IP addresses and localhost. Adjust the pattern to be stricter or looser depending on your use case.
Example
/https?://(www.)?[-a-zA-Z0-9@:%._+~#=]{1,256}.[a-zA-Z0-9()]{1,6}([-a-zA-Z0-9()@:%_+.~#?&/=]*)/g
# Test cases:
https://example.com
http://www.site.co.uk/path?q=1#anchor
https://sub.domain.org:8080/api/v2
not-a-url
ftp://wrong-protocol.comFAQ
- Should I use the g flag for URL matching?
- Use the g (global) flag when you want to find all URLs in a block of text. Without it, the regex only returns the first match.
- Does this pattern match localhost URLs?
- Standard URL regex patterns require a TLD, which localhost lacks. Add a separate branch for localhost and IP addresses if you need to match development URLs.
- How do I extract just the domain from a URL?
- Use a capturing group around the domain segment of the pattern. The tester shows capture group values for each match so you can see what each group extracted.
Related Examples
Regex Pattern for Email Validation
Email validation regex is one of the most commonly written and miswritten patter...
Regex Pattern for IP AddressesIP address validation is trickier than it looks because each octet must be betwe...
Regex Pattern for HTML TagsMatching HTML tags with regex is useful for stripping markup from text content o...