user2120910
user2120910

Reputation: 404

C# Replace URL Regex

I am trying to pull a URL out of a string and use it later to create a Hyperlink. I would like to be able to do the following: - determine if the input string contains a URL - remove the URL from the input string - store the extracted URL in a variable for later use

Can anyone help me with this?

Upvotes: 0

Views: 1587

Answers (2)

Replace input with your input

        string input = string.Empty;
        var matches = Regex.Matches(input,
                      @"/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[.\!\/\\w]*))?)/");
        List<string> urlList = (matches.Cast<object>().Select(match => match.ToString())).ToList();

Upvotes: 0

msantiago
msantiago

Reputation: 346

Here is a great solution for recognizing URLs in popular formats such as:

The regular expression used is:

/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/

However, I would recommend you go to http://blog.mattheworiordan.com/post/13174566389/url-regular-expression-for-links-with-or-without-the to see the working example.

Upvotes: 3

Related Questions