Donate

Regular Expression Extract Url From String Using Regex.Matches() In C#

Here's how to extract url(s) from a string or document using Regex.Matches() method. The Regex.Matches() method returns an array object MatchCollection in which you can access individual elements using it's index.
Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
string pattern = "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?";
string Input = "<<abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ\"abcd\" href=\"https://mediatemple.net\"" + 
               "Sample text for testing>http://regexr.com/foo.html?q=bar>";
 
string url1 = string.Empty;
string url2 = string.Empty;
if (Regex.Matches(Input, pattern).Count > 0) 
{
    MatchCollection matches = Regex.Matches(Input, pattern);
    url1 = matches[0].Value;
    url2 = matches[1].Value;
}

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input