Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting substring between two separators in an arbitrary position

Tags:

c#

.net

regex

linq

I have following string:

string source = "Test/Company/Business/Department/Logs.tvs/v1";

The / character is the separator between various elements in the string. I need to get the last two elements of the string. I have following code for this purpose. This works fine. Is there any faster/simpler code for this?

CODE

    static void Main()
    {
        string component = String.Empty;
        string version = String.Empty;
        string source = "Test/Company/Business/Department/Logs.tvs/v1";
        if (!String.IsNullOrEmpty(source))
        {
            String[] partsOfSource = source.Split('/');
            if (partsOfSource != null)
            {
                if (partsOfSource.Length > 2)
                {
                    component = partsOfSource[partsOfSource.Length - 2];
                }

                if (partsOfSource.Length > 1)
                {
                    version = partsOfSource[partsOfSource.Length - 1];
                }
            }
        }

        Console.WriteLine(component);
        Console.WriteLine(version);
        Console.Read();
    }
like image 270
LCJ Avatar asked Jan 23 '13 16:01

LCJ


1 Answers

Why no regular expression? This one is fairly easy:

.*/(?<component>.*)/(?<version>.*)$

You can even label your groups so for your match all you need to do is:

component = myMatch.Groups["component"];
version = myMatch.Groups["version"];
like image 69
Matt Burland Avatar answered Nov 14 '22 23:11

Matt Burland