Quantcast
Channel: DevtheWeb.NET » .NET
Viewing all articles
Browse latest Browse all 7

My URL Pattern

$
0
0

I needed a url pattern that recognizes the following urls:

http://site.com

www.site.com

https://site.com

https://www.site.com

Even more, I wanted after url detection, it to be replaced with:

http://site.com -> http://site.com

www.site.com -> http://www.site.com

https://site.com -> https://site.com

https://www.site.com -> https://www.site.com

I use Regex’s Replace method. It detects all urls and replaces them with the correct format. Here is the full example:

string originalText;

string convertedText = Regex.Replace(originalText,
@”((http(?<http1>(s?))://(?<www1>(www.)))|(http(?<http2>(s?))://)|((?<www2>(www.))))(?<url>([wd:#@%/;$()~_?+-=\.&]*))”,
@”http${http1}${http2}://${www1}${www2}${url}”);

P.S. I hope that the example above could be useful to someone else, too. If you find some bug or suggestion, I’ll be very thankful to hear how it can be fixed :)


Viewing all articles
Browse latest Browse all 7

Trending Articles