我嘗試使用IndexOf來簡化一些遺留代碼以從行中檢索GUID。我可以進一步簡化下面的代碼來擺脫使用guids.Any和guids.First?從C#中提取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;
}
下面的樣本中給出的遺留代碼編譯:
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;
}
}
}
你爲什麼不使用guid.tryparse –
['Guid.TryParse()'](https://msdn.microsoft.com/en-us/library/system.guid.tryparse(v = vs。 110).aspx)會比嘗試使用自己的正則表達式來解析GUID好得多 – Liam
是啊,只需使用xdoc獲取值並解析guid –