我多么喜欢正则表达式!
我有一个字符串,它将是 XML 的一种损坏形式,例如:
<Category>DIR</Category><Location>DL123A</Location><Reason>Because</Reason><Qty>42</Qty><Description>Some Desc</Description><IPAddress>127.0.0.1</IPAddress>
所有内容都在一行中,但是“标题”通常会有所不同。
所以我需要做的是从上面的字符串中提取所有信息,将其放入字典/哈希表中
--
string myString = @"<Category>DIR</Category><Location>DL123A</Location><Reason>Because</Reason><Qty>42</Qty><Description>Some Desc</Description><IPAddress>127.0.0.1</IPAddress>";
//this will extract the name of the label in the header
Regex r = new Regex(@"(?<header><[A-Za-z]+>?)");
//Create a collection of matches
MatchCollection mc = r.Matches(myString);
foreach (Match m in mc)
{
headers.Add(m.Groups["header"].Value);
}
//this will try and get the values.
r = new Regex(@"(?'val'>[A-Za-z0-9\s]*</?)");
mc = r.Matches(myString);
foreach (Match m in mc)
{
string match = m.Groups["val"].Value;
if (string.IsNullOrEmpty(match) || match == "><" || match == "> <")
continue;
else
values.Add(match);
}
-- 我从以前使用正则表达式的工作中尽可能地破解了它。 但它并没有真正按照我想要的方式工作。
“标题”也将尖括号拉入。
'value' 引入了很多空值(因此循环中的狡猾 if 语句)。它也不适用于带有句点、逗号、空格等的字符串。
如果我可以将这两个语句结合起来,这样我就不必在正则表达式中循环两次,那就更好了。
谁能给我一些我可以改进的信息?
请您参考如下方法:
如果它看起来像 XML,为什么不使用 .net 的 XML 解析器功能?您需要做的就是在其周围添加一个根元素:
string myString = @"<Category>DIR</Category><Location>DL123A</Location><Reason>Because</Reason><Qty>42</Qty><Description>Some Desc</Description><IPAddress>127.0.0.1</IPAddress>";
var values = new Dictionary<string, string>();
var xml = XDocument.Parse("<root>" + myString + "</root>");
foreach(var e in xml.Root.Elements()) {
values.Add(e.Name.ToString(), e.Value);
}
