tags:

views:

47

answers:

3
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]

A: 
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);
+1  A: 

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)

polemon
A: 

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

liho1eye