下面的代码运行良好,目标是在 XML 文件中查找 GUID 字符串。因此它会找到字符串 A03DD607-90BF-4077-ADA8-C6E76F9D4759
例如,但现在我尝试将正则表达式更改为仅查找:
id="A03DD607-90BF-4077-ADA8-C6E76F9D4759"
而不是
A03DD607-90BF-4077-ADA8-C6E76F9D4759
这是我的代码:
//obtain all GUIDs in the XML file
using (StreamReader sr = File.OpenText(xmlFile))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
MatchCollection guids = Regex.Matches(s, @"(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}");
for (int i = 0; i < guids.Count; i++)
{
Console.WriteLine(guids[i].Value);
guidList.Add(guids[i].Value.ToUpper());
}
}
}
最佳答案
您可以使用以下代码替换相应的代码行:
MatchCollection guids = Regex.Matches(s, @"id=""\{?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}}?""");
在 C# verbatim string literals 中(请参阅此链接中的第 2 点),看起来像 @"..."
,文字引号必须加倍。
{0,1}
限制量词可以安全地更改为 ?
(出现 1 次或 0 次)。
字符类之外的 -
字符(不在 [...]
构造内部)不必转义。
参见 regex demo 。
关于c# - 正则表达式用于在 txt 文件中查找附加有 "id="的 GUID 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29245115/