我正在尝试创建一个Sprache解析器,其中应将部分输入解析为字典
input=some/fixed/stuff;and=a;list=of;arbitrary=key;value=pairs
该and=a;list=of;arbitrary=key;value=pairs
部分应该以 Dictionary<string,string> 结尾。
为此我有
public static Parser<string> Key = Parse.CharExcept('=').Many().Text();
public static Parser<string> Value = Parse.CharExcept(';').Many().Text();
public static Parser<KeyValuePair<string, string>> ParameterTuple =
from key in Key
from eq in Parse.Char('=')
from value in Value
select new KeyValuePair<string, string>(key, value);
和扩展方法
public static IEnumerable<T> Cons<T>(this T head, IEnumerable<T> rest)
{
yield return head;
foreach (var item in rest)
yield return item;
}
public static Parser<IEnumerable<T>> ListDelimitedBy<T>(this Parser<T> parser, char delimiter)
{
return
from head in parser
from tail in Parse.Char(delimiter).Then(_ => parser).Many()
select head.Cons(tail);
}
(从示例中复制)
然后我尝试了
public static Parser<IEnumerable<KVP>> KeyValuePairList = KVPair.ListDelimitedBy(';'); // KVP is just an alias for KeyValuePair<string,string>
现在我被困在如何做类似的事情上
public static Parser<???> Configuration =
from fixedstuff in FixedStuff
from kvps in Parse.Char(';').Then(_ => KeyValuePairList)
select new ???(fixedstuff, MakeDictionaryFrom(kvps))
或类似的东西。
我如何将任意 key=value[;] 对解析为字典?