Regular expression pattern to match URL with or without http://www

Viewed 80243

I'm not very good at regular expressions at all.

I've been using a lot of framework code to date, but I'm unable to find one that is able to match a URL like http://www.example.com/etcetc, but it is also is able to catch something like www.example.com/etcetc and example.com/etcetc.

13 Answers

You can try this:

r"(http[s]:\/\/)?([\w-]+\.)+([a-z]{2,5})(\/+\w+)? "

Selection:

  1. may be start with http:// or https:// (optional)

  2. anything (word) end with dot (.)

  3. followed by 2 to 5 character [a-z]

  4. followed by "/[anything]" (optional)

  5. followed by space

I have been using the following, which works for all my test cases, as well as fixes any issues where it would trigger at the end of a sentence preceded by a full-stop (end.), or where there were single character initials, such as 'C.C. Plumbing'.

The following regex contains multiple {2,}s, which means two or more matches of the previous pattern.

((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]{2,}\.([a-zA-Z0-9\&\.\/\?\:@\-_=#]){2,}

Matches URLs such as, but not limited to:

Does not match non-URLs such as, but not limited to:

  • C.C Plumber
  • A full-stop at the end of a sentence.
  • Single characters such as a.b or x.y

Please note: Due to the above, this will not match any single character URLs, such as: a.co, but it will match if it is preceded by a URL scheme, such as: http://a.co.

I was getting so many issues getting the answer from anubhava to work due to recent PHP allowing $ in strings and the preg match wasn't working.

Here is what I used:

// Regular expression
$re = '/((https?|ftp):\/\/)?([a-z0-9+!*(),;?&=.-]+(:[a-z0-9+!*(),;?&=.-]+)?@)?([a-z0-9\-\.]*)\.(([a-z]{2,4})|([0-9]{1,3}\.([0-9]{1,3})\.([0-9]{1,3})))(:[0-9]{2,5})?(\/([a-z0-9+%-]\.?)+)*\/?(\?[a-z+&$_.-][a-z0-9;:@&%=+\/.-]*)?(#[a-z_.-][a-z0-9+$%_.-]*)?/i';
// Match all
preg_match_all($re, $blob, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
// The first element of the array is the full match

This PHP Composer package URL highlight is doing a good job in PHP:

<?php
    use VStelmakh\UrlHighlight\UrlHighlight;

    $urlHighlight = new UrlHighlight();
    $matches = $urlHighlight->getUrls($string);
?>

Regex if you want to ensure URL starts with HTTP/HTTPS:

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

If you do not require HTTP protocol:

[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
Related