1

I want to extract the domain name from the url. For example for www.Edmunds.com/Toyota_Camry_Hybrid or http://jido.com I want to have www.Edmunds.com and jido.com

I have written the following regular expression:

Regex.Replace(Url, @"^([a-zA-Z]+:\/\/)?([^\/]+)\/.*?$", "$2");

It works fine for the first link but for the second link I get: http:

Could someone please help me with this?

Abbas
  • 14,186
  • 6
  • 41
  • 72
Rachel
  • 305
  • 2
  • 12
  • 3
    Possible Duplicate: http://stackoverflow.com/questions/15713542/elegant-way-parsing-url – arco444 Aug 27 '14 at 10:51
  • It is not a duplicate since, OP is clearly asking for a regular expression for extracting domain name from the url, not for an _"elegant way for parsing url"_. Fact, that the highest pointed answer is the same as in the linked question is irrelevant here, because it does not answer the question. – Prolog Dec 20 '19 at 15:19

2 Answers2

6

You can use the Uri class to get specific parts of a URL.

var uri = new Uri("www.Edmunds.com/Toyota_Camry_Hybrid");
Console.WriteLine(uri.Host);
Tom
  • 2,321
  • 2
  • 18
  • 29
  • 1
    You didn't answer the question. OP is clearly asking for a regular expression for extracting a domain name from url. – Prolog Dec 20 '19 at 15:21
  • 1
    If you take a very pedantic view of the question then no, I didn't, but looking at the context of what OP was asking, then yes I did answer it - they weren't specifically looking to solve it via Regex, but just wanted a way to get the host. I think the fact that OP marked this as answered probably validates that assumption. I do appreciate though if you got here via Google then this answer isn't what you're looking for. – Tom Dec 23 '19 at 13:30
  • Yes, you guessed correctly. I came across three or so similar questions, all basically suggesting using `Uri`. I eventually found the wanted regular expression, but it honestly required spending quite some time searching. – Prolog Dec 23 '19 at 20:16
  • And yet, unfortunately, you didn't see it fit to help people in your position by providing a link to the answer, or the regex itself – Moustachiste Jun 02 '22 at 19:31
0
(?=http*).*\/(.*)|(.*?)\/

You can try this. See demo.

Abbas
  • 14,186
  • 6
  • 41
  • 72
vks
  • 67,027
  • 10
  • 91
  • 124