简体   繁体   中英

Regex to extract domain from a url

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?

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);
(?=http*).*\/(.*)|(.*?)\/

You can try this. See demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM