senzacionale
senzacionale

Reputation: 20916

Regex IP for URL problem

const string strRegex = @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}"
   "(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$";
Regex rgxUrl = new Regex(strRegex, RegexOptions.Compiled
   |RegexOptions.IgnoreCase);

If my URL is http://89.212.232.65 then this regex for checking URL fails. How must I change the regex so that will also work for IP addresses?

[I took editing liberties with the strRegex definition which is all one contiguous constant -msw]

Upvotes: 1

Views: 711

Answers (3)

Ilia G
Ilia G

Reputation: 10211

Presumably you are doing some kind of validation? Or trying to extract host name? You don't need regex for this. Use Uri or UriBuilder classes

Upvotes: 0

Jeff Mattfield
Jeff Mattfield

Reputation:

const string strRegex = 
    @"^(http|https|ftp)\://" +
    @"(([a-zA-Z0-9-.]+\.[a-zA-Z]{2,3})|([0-2]*\d*\d\.[0-2]*\d*\d\.[0-2]*\d*\d\.[0-2]*\d*\d))" +
    @"(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9-._\?\,\'/\+&%\$#\=~])*[^.\,)(\s]$";
Regex rgxUrl = new Regex(strRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase);

Upvotes: 0

polemon
polemon

Reputation: 4772

this one . in +.[a-zA-Z]{2,3} doesn't make sense, you probably mean \.

This here works well for the first portion:

/^(https?|ftp):\/\/([-\w.]+\.[a-zA-Z]{2,3})|((\d{1,3}\.){3}\d{1,3})/

(PCRE)

Upvotes: 1

Related Questions