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

标签 c# .net regex linq

我有以下字符串:

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

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

代码

    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();
    }

最佳答案

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

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

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

component = myMatch.Groups["component"];
version = myMatch.Groups["version"];

关于c# - 在任意位置的两个分隔符之间获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14484567/

相关文章:

python - 替换花括号中的逗号

c# - 使用 C# 读取 sql 查询

.net - 如何将库项目中的 ASP.NET Core 3.0 类型用于共享 Controller 、中间件等?

regex - 类似 grep 的 postgres 查询

.net - Winforms/WPF 应用程序可以充当 HTTP 服务器吗?

c# - 如何使用 C# 安全连接到 MySQL,反编译时不显示任何信息

python - 如果字符串操作变成 "complicated",我是否应该继续使用 str.replace 而不是 re.sub

c# - Visual Studio 设计器中的别名和命名空间冲突

c# - 调用 dll 方法时出现 FatalExecutionEngineError

c# - 在 RavenDB 中加密和解密索引字段