can anyone help me find out url from given paragraph using regex c#
Note: Paragraph may contain string and url also
Input like this
"My website http://www.google.com/myMail/1212 this is my 开发者_如何学Gofavorite website"
out put looks:
My website <a href='http://www.google.com/myMail/1212'>http://www.google.com/myMail/1212</a> this is my favorite website
Stolen from here:
public string[] ExtractURLs(string str)
{
// match.Groups["name"].Value - URL Name
// match.Groups["url"].Value - URI
string RegexPattern = @"<a.*?href=[""'](?<url>.*?)[""'].*?>(?<name>.*?)</a>"
// Find matches.
System.Text.RegularExpressions.MatchCollection matches
= System.Text.RegularExpressions.Regex.Matches(str, RegexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
string[] MatchList = new string[matches.Count];
// Report on each match.
int c = 0;
foreach (System.Text.RegularExpressions.Match match in matches)
{
MatchList[c] = match.Groups["url"].Value;
c++;
}
return MatchList;
}
Googling can really pay off you know
Taken straight from RegexBuddy:
resultString = Regex.Replace(subjectString, @"\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[A-Z0-9+&@#/%=~_|]", "<a href=\"$0\">$0</a>", RegexOptions.IgnoreCase);
Note that the protocol is mandatory.
Thank you Mr. M.edmondson
Googling helped me , got the answer below
string FindUrl(string url)
{
Regex r1= new Regex("((http://|www\\.)([A-Z0-9.-:]{1,})\\.[0-9A-Z?;~&#=\\-_\\./]{2,})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
MatchCollection mc = r1.Matches(url);
foreach (Match m in mc)
{
url = url.Replace(m.Value, "<a href='" + m.Value + "'>" + m.Value + "</a>");
}
return url;
}
精彩评论