【发布时间】:2011-04-01 13:40:20
【问题描述】:
我希望你们能帮助我。 我正在使用 C# .Net 4.0
我想验证类似的文件结构
const string dataFileScr = @"
Start 0
{
Next = 1
Author = rk
Date = 2011-03-10
/* Description = simple */
}
PZ 11
{
IA_return()
}
GDC 7
{
Message = 6
Message = 7
Message = 8
Message = 8
RepeatCount = 2
ErrorMessage = 10
ErrorMessage = 11
onKey[5] = 6
onKey[6] = 4
onKey[9] = 11
}
";
到目前为止,我设法构建了这个正则表达式模式
const string patternFileScr = @"
^
((?:\[|\s)*
(?<Section>[^\]\r\n]*)
(?:\])*
(?:[\r\n]{0,}|\Z))
(
(?:\{) ### !! improve for .ini file, dont take {
(?:[\r\n]{0,}|\Z)
( # Begin capture groups (Key Value Pairs)
(?!\}|\[) # Stop capture groups if a } is found; new section
(?:\s)* # Line with space
(?<Key>[^=]*?) # Any text before the =, matched few as possible
(?:[\s]*=[\s]*) # Get the = now
(?<Value>[^\r\n]*) # Get everything that is not an Line Changes
(?:[\r\n]{0,})
)* # End Capture groups
(?:[\r\n]{0,})
(?:\})?
(?:[\r\n\s]{0,}|\Z)
)*
";
和c#
Dictionary <string, Dictionary<string, string>> DictDataFileScr
= (from Match m in Regex.Matches(dataFileScr,
patternFileScr,
RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline)
select new
{
Section = m.Groups["Section"].Value,
kvps = (from cpKey in m.Groups["Key"].Captures.Cast().Select((a, i) => new { a.Value, i })
join cpValue in m.Groups["Value"].Captures.Cast().Select((b, i) => new { b.Value, i }) on cpKey.i equals cpValue.i
select new KeyValuePair(cpKey.Value, cpValue.Value)).OrderBy(_ => _.Key)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
}).ToDictionary(itm => itm.Section, itm => itm.kvps);
它适用于
const string dataFileScr = @"
Start 0
{
Next = 1
Author = rk
Date = 2011-03-10
/* Description = simple */
}
GDC 7
{
Message = 6
RepeatCount = 2
ErrorMessage = 10
onKey[5] = 6
onKey[6] = 4
onKey[9] = 11
}
";
换句话说
Section1
{
key1=value1
key2=value2
}
Section2
{
key1=value1
key2=value2
}
,但是
DictDataFileScr["GDC 7"]["Message"] = "6|7|8|8"
DictDataFileScr["GDC 7"]["ErrorMessage"] = "10|11"
....
[Section1]
key1 = value1
key2 = value2
[Section2]
key1 = value1
key2 = value2
...
....
PZ 11
{
IA_return()
}
.....
【问题讨论】:
-
如果你能将你的案例减少到几行,也许人们可以更好地帮助你
-
你能发一些其他的例子吗
-
Soo ah,你想告诉我为什么
\s*(\[[^\S\n]*)?(?<Section>\w+(?:[^\S\n]+ \w+)*)(?(1)[^\S\n]*\]|)\s*(?(1)|\{)(?:\s*(?:\/\*.*?\*\/|(?<Key>\w[\w\[\]]*(?:[^\S\n]+[\w\[\]]+)*)[^\S\n]*=[^\S\n]*(?<Value>[^\n]*)|(?(1)|[^{}\n]*))\s*)*(?(1)|\})只用单行('.' 点也表示换行符)对你不起作用,我的意思是我在给你扔骨头这里。我在 dot net 中阅读了有关 Collections 的信息,这绝对应该这样做。我可以被雇来做你能想象到的最具挑战性的事情。这个正则表达式的微妙之处是崇高的。如果您知道自己在看什么,它的流程简单而强大。
标签: c# .net regex linq dictionary