在两个分隔符之间获取任意位置的子字符串

LCJ*_*LCJ 5 .net c# regex linq

我有以下字符串:

string source = "Test/Company/Business/Department/Logs.tvs/v1";
Run Code Online (Sandbox Code Playgroud)

/字符是字符串中各种元素之间的分隔符.我需要获取字符串的最后两个元素.我为此目的有以下代码.这很好用.有没有更快/更简单的代码?

    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();
    }
Run Code Online (Sandbox Code Playgroud)

Mat*_*and 4

为什么没有正则表达式?这个相当简单:

.*/(?<component>.*)/(?<version>.*)$
Run Code Online (Sandbox Code Playgroud)

您甚至可以为您的组添加标签,因此对于您的比赛,您需要做的就是:

component = myMatch.Groups["component"];
version = myMatch.Groups["version"];
Run Code Online (Sandbox Code Playgroud)

  • ...好吧,今天我了解到您可以执行类似 `Regex.Match(source, "/(.*?)/(.*?)$", RegexOptions.RightToLeft)` 的操作,甚至可以不使用 `$`这个案例。 (2认同)