从C#行中提取GUID

Les*_*ite 4 c#

我尝试使用IndexOf简化一些遗留代码,以从行中检索GUID。我可以进一步简化下面的代码以摆脱使用guids.Any和guids.First吗?

// Code using regular expression
private static string RetrieveGUID2(string[] lines)
{
    string guid = null;
    foreach (var line in lines)
    {
        var guids = Regex.Matches(line, @"[{(]?[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?")
            .Cast<Match>().Select(m => m.Value);
        if (guids.Any())
        {
            guid = guids.First();
            break;
        }
    }
    return guid;
}
Run Code Online (Sandbox Code Playgroud)

下面是编译示例中给出的旧版代码:

using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var lines = new[]
            {
                "</ItemGroup>\n",
                "<PropertyGroup\n",
                "Label = \"Globals\">\n",
                "<ProjectGuid>{A68615F1-E672-4B3F-B5E3-607D9C18D1AB}</ProjectGuid>\n",
                "</PropertyGroup>\n"
            };

            Console.WriteLine(RetrieveGUID(lines));
            Console.WriteLine(RetrieveGUID2(lines));
        }

        // Legacy code
        private static string RetrieveGUID(string[] lines)
        {
            string guid = null;
            foreach (var line in lines)
            {
                var startIdx = line.IndexOf("<ProjectGuid>{", StringComparison.Ordinal);
                if (startIdx < 0) continue;
                var endIdx = line.IndexOf("</ProjectGuid>", StringComparison.Ordinal);
                if (endIdx < 0) continue;
                startIdx += "<ProjectGuid>".Length;
                var guidLen = endIdx - startIdx;
                guid = line.Substring(startIdx, guidLen);
                break;
            }
            return guid;
        }

        // Code using regular expression
        private static string RetrieveGUID2(string[] lines)
        {
            string guid = null;
            foreach (var line in lines)
            {
                var guids = Regex.Matches(line, @"[{(]?[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?")
                    .Cast<Match>().Select(m => m.Value);
                if (guids.Any())
                {
                    guid = guids.First();
                    break;
                }
            }
            return guid;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*nko 5

是的你可以。因为您只返回了正则表达式的第一个匹配项,所以可以使用Regex.Match代替Regex.Matches

private static string RetrieveGUID2(string[] lines)
{
    foreach (var line in lines)
    {
        var match = Regex.Match(line, @"[{(]?[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?");
        if (match.Success)
          return match.Value;
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)