Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to match a URL with optional 'www' and protocol

I'm trying to write a regexp.

some background info: I am try to see if the REQUEST_URI of my website's URL contains another URL. like these:

  • http://mywebsite.com/google.com/search=xyz

However, the url wont always contain the 'http' or the 'www'. so the pattern should also match strings like:

  • http://mywebsite.com/yahoo.org/search=xyz
  • http://mywebsite.com/www.yahoo.org/search=xyz
  • http://mywebsite.com/msn.co.uk'
  • http://mywebsite.com/http://msn.co.uk'

there are a bunch of regexps out there to match urls but none I have found do an optional match on the http and www.

i'm wondering if the pattern to match could be something like:

^([a-z]).(com|ca|org|etc)(.)

I thought maybe another option was to perhaps just match any string that had a dot (.) in it. (as the other REQUEST_URI's in my application typically won't contain dots)

Does this make sense to anyone? I'd really appreciate some help with this its been blocking my project for weeks.

Thanks you very much -Tim

like image 231
TimFelix Avatar asked Sep 13 '25 00:09

TimFelix


2 Answers

I suggest using a simple approach, essentially building on what you said, just anything with a dot in it, but working with the forward slashes too. To capture everything and not miss unusual URLs. So something like:

^((?:https?:\/\/)?[^./]+(?:\.[^./]+)+(?:\/.*)?)$

It reads as:

  • optional http:// or https://
  • non-dot-or-forward-slash characters
  • one or more sets of a dot followed by non-dot-or-forward-slash characters
  • optional forward slash and anything after it

Capturing the whole thing to the first grouping.

It would match, for example:

  • nic.uk
  • nic.uk/
  • http://nic.uk
  • http://nic.uk/
  • https://example.com/test/?a=bcd

Verifying they are valid URLs is another story! It would also match:

  • index.php

It would not match:

  • directory/index.php

The minimal match is basically something.something, with no forward slash in it, unless it comes at least one character past the dot. So just be sure not to use that format for anything else.

To match an optional part, you use a question mark ?, see Optional Items.

For example to match an optional www., capture the domain and the search term, the regular expression could be

(www\.)?(.+?)/search=(.+)

Although, the question mark in .+? is a non-greedy quantifier, see http://www.regular-expressions.info/repeat.html.

like image 31
Olaf Dietsche Avatar answered Sep 15 '25 15:09

Olaf Dietsche