简体   繁体   中英

RegEx to extract a sub level from url

i have the following set of Urls:

http://test/mediacenter/Photo Gallery/Conf 1/1.jpg
http://test/mediacenter/Photo Gallery/Conf 2/3.jpg
http://test/mediacenter/Photo Gallery/Conf 3/Conf 4/1.jpg

All i want to do is to extract the Conf 1, Conf 2,Conf 3 from the urls, the level after 'Photo Gallery' (Urls are not static, they share common level which is Photo Gallery)

Any help is appreciated

Is it necessary to use Regex? You can get it without using Regex like this

string str= @"http://test/mediacenter/Photo Gallery/Conf 1/1.jpg";
var z=qq.Split('/')[5];

or

var x= new Uri(str).Segments[3];

This ought to do you:

var s = @"http://test/mediacenter/Photo Gallery/Conf 11/1.jpg";
var regex = new Regex(@"(Conf \d*)");
var match = regex.Match(s);
Console.WriteLine(match.Groups[0].Value); // Prints a

Of course, you'd have to be confident the 'Conf x' (where x is a number) wasn't going to be elsewhere in the URL.

This will improve it slightly by stripping off multiple folders (Conf 3/Conf 4) in your example.

var regex = new Regex(@"((Conf \d*/*)+)");

It leaves the trailing / though.

Try a RegEx like this.

Conf[^\/]*

This should give you all "Conf" Parts of the URLs.

I hope that helps.

No need for regex.

    string testCase = "http://test/mediacenter/Photo Gallery/Conf 1/1.jpg";
    string urlBase = "http://test/mediacenter/Photo Gallery/";

    if(!testCase.StartsWith(urlBase))
    {
        throw new Exception("URL supplied doesn't belong to base URL.");
    }

    Uri uriTestCase = new Uri(testCase);
    Uri uriBase = new Uri(urlBase);

    if(uriTestCase.Segments.Length > uriBase.Segments.Length)
    {
        System.Console.Out.WriteLine(uriTestCase.Segments[uriBase.Segments.Length]);
    }
    else
    {
        Console.Out.WriteLine("No child segment...");
    }

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