gpt4 book ai didi

c# - 在附有 "id="的 txt 文件中查找 GUID 字符串的正则表达式

转载 作者:行者123 更新时间:2023-11-30 21:59:28 29 4
gpt4 key购买 nike

下面的代码运行良好,目标是在 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# - 在附有 "id="的 txt 文件中查找 GUID 字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29245115/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com