URL Regex
Find web addresses in text with a short pattern, and see exactly where it stops before you put it in code.
URL Regex
Pulling links out of logs, chat exports or scraped text is a job for a regular expression, and the pattern should be short enough to read. This page opens the Regex Tester with the URL (http/https) pattern from the Pattern library, https?:\/\/[^\s/$.?#][^\s]*, with the flags gi.
How the pattern reads
| Part | Meaning |
|---|---|
https? | http, with an optional s |
:\/\/ | The colon and the two slashes, escaped so the pattern also works between slashes in code |
[^\s/$.?#] | The first character of the host name: anything but a space, slash, dollar sign, dot, question mark or hash |
[^\s]* | Everything else up to the next space |
gi | Find every link, in any letter case |
What it catches and what it misses
| Text | Result |
|---|---|
https://logicutil.com/tool/regex-tester | The whole address |
http://example.org/page?q=1#top | The whole address, query and fragment included |
http://localhost:8080/x | The whole address, port included |
HTTPS://EXAMPLE.COM/X | Matched, because of the i flag |
https://例子.测试/路径 | Matched: non-Latin domains and paths are kept |
Visit https://example.com. | https://example.com., with the full stop |
(https://example.com/a) | https://example.com/a), with the bracket |
www.example.com | No match: there is no scheme |
ftp://files.example.com | No match: only http and https |
A tighter version
To leave trailing punctuation out, end the match with a lookahead: https?:\/\/[^\s/$.?#][^\s]*?(?=[\].,;:!?)]*(?:\s|$)). It takes the shortest run that is followed only by punctuation and then a space or the end of the text, so Visit https://example.com. gives https://example.com and (https://example.com/a) gives https://example.com/a. The price is that a link which really ends in a bracket, as some Wikipedia addresses do, loses it.
Finding links is not validating them
A pattern like this answers "does this text contain something that looks like a link", not "is this a working address". For a single value in JavaScript, new URL(value) is stricter: it throws on https:// with no host at all. Use the regex to find candidates in text, then let new URL() or your server decide.
Related pages
Turn found links into Markdown with [$&]($&) on the regex find and replace page, and see how the flags behave on the JavaScript regex tester. Email addresses have pitfalls of their own, covered in the email regex guide.