$devtoolkit.sh/examples/regex/url-matching

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.com
[ open in Regex Tester → ]

FAQ

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

/examples/regex/url-matchingv1.0.0