Regular Expressions 101

Community Patterns

Validate URLs

1

Regular Expression
PCRE (PHP <7.3)

`
(?(DEFINE) (?<PROTOCOL>[^:/#?\s]+://) (?<LOGIN>[^:@/#?\s]+(?::[^@/#?\s]+)?@) (?<TEXT_DOMAIN>[^./#?\s-:]+(?:-[^./#?\s-:]+)?\.) (?<IP_DOMAIN> (?&NOT_RESERVED_IP) (?: (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. ){3} (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) ) (?<NOT_RESERVED_IP> (?!(?:1?0|224)(?:\.\d{1,3}){3}| (?:192\.168|172\.16)(?:\.\d{1,3}){2} ) ) (?<TLD>[^/#?\s.\d:-]+) (?<PORT>:\d{1,4}) (?<PATH>/(?:[^/\s&#?]*/?)+) (?<QUERY> \? (?: [^\s=]+(?:=[^&\s]*)? (?:&[^\s=]+(?:=[^&\s]*)?)* )? ) (?<HASH>\#.*) ) ^ (?&PROTOCOL) (?&LOGIN)? (?:(?&TEXT_DOMAIN)+(?&TLD)|(?&IP_DOMAIN)) (?&PORT)? (?&PATH)? (?&QUERY)? (?&HASH)? $
`
gmx

Description

Someone on IRC posted the following site: https://mathiasbynens.be/demo/url-regex which challgenged me to write a decent regex to match valid URLs in that list. This regex works in both pcre and javascript (you'll have to replace the pcre-specific syntax to make it work in JS).

Don't actually use this though, validate your URLs in a sane manner instead.

Submitted by Firas Dib - 9 years ago