开发者

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 cont开发者_开发百科iguous constant -msw]


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)


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);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜