Regex for URL
A usable URL regex is ^https?:\/\/[^\s/$.?#][^\s]*$ : http or https, a host that does not start with a dot or slash, then anything except whitespace. To extract links from text use https?:\/\/[^\s<>]*[^\s<>.,;:] with the g flag. For strict validation in JavaScript, prefer new URL(string) inside a try block.
Syntax
/^https?:\/\/[^\s/$.?#][^\s]*$/Examples
/^https?:\/\/[^\s/$.?#][^\s]*$/.test("https://example.com/path?q=1")Result: true
/^https?:\/\/[^\s/$.?#][^\s]*$/.test("example.com")Result: false
The scheme is required. Use (?:https?:\/\/)? to make it optional.
"See https://a.com/x and http://b.org.".match(/https?:\/\/[^\s<>]*[^\s<>.,;:]/g)Result: ["https://a.com/x", "http://b.org"]
The last class excludes punctuation so the sentence period is not swallowed.
"https://example.com:8080/docs/intro?x=1".match(/^(https?):\/\/([^/:]+)(?::(\d+))?(\/[^?#]*)?/)Result: ["https://example.com:8080/docs/intro", "https", "example.com", "8080", "/docs/intro"]
Groups: scheme, host, optional port, optional path.
Common mistakes
- Unescaped slashes inside a JavaScript regex literal end the pattern early; write \/ or build the regex from a string.
- Requiring www\. rejects most URLs; make it optional with (?:www\.)? or leave it out.
- Capturing the trailing period or comma when extracting from prose; end the pattern with a class that excludes . , ; : and ).
- Writing example.com without escaping the dot, which also matches examplexcom; escape literal dots as \.
Practice Regex for URL
These drills check your answer on live data, free, no account needed.
- Host names from URLsFind the first http or https URL on the line and capture its host name in group 1: everything after :// up to a slash, colon, question mark, hash or whitespace.
- URL slugsThe whole line must match. Match a URL slug: lowercase letters and digits in chunks joined by single hyphens. No hyphen at the start or end and no doubled hyphens.
- Escaping: a price like $4.99The whole line must match. Match a dollar sign, one or more digits, a period and exactly two digits.
Questions
What is the regex for a URL without http?
Make the scheme optional: ^(?:https?:\/\/)?(?:www\.)?[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+(?:\/\S*)?$ matches example.com, www.example.com/page and https://example.com.
How do I extract the domain from a URL with regex?
Use ^https?:\/\/([^/:?#]+) and read group 1, which gives example.com from https://example.com:8080/path. In JavaScript, new URL(u).hostname is simpler and handles edge cases.
Should I validate URLs with regex or new URL()?
Use new URL() for validation in JavaScript; it parses exactly what browsers accept. Use the regex when you need to find URLs inside text or when you work in a tool that only offers regex, such as a spreadsheet or SQL.
Related
- Regex for emailA practical email regex for JavaScript and other engines, how to validate a whole field, extract addresses from text, and why RFC-perfect patterns are a trap.
- Escaping special charactersThe regex metacharacters that must be escaped, how to match a literal dot, dollar, plus or slash, what changes inside brackets, and how to escape user input.
- Non-capturing group (?:...)How (?:...) groups for quantifiers and alternation without a numbered capture, why that keeps group numbers stable, and how it changes findall in Python.
- Regex for HTML tagsHow to remove HTML tags with <[^>]+>, list tag names, read an href value, match the content of one tag lazily, and why regex is not an HTML parser.
Previous: Regex for date YYYY-MM-DDNext: Regex for IPv4 address