You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Sprache解析‘accept-version:V1.2’并提取对应字段?

解决Sprache解析"accept-version:V1.2"失败的问题

你的解析失败核心原因是当前的Text解析器规则不对:它用Parse.CharExcept('"').Many().Text(),只会排除双引号,不会排除冒号。解析headerStr时,这个规则会把整个字符串accept-version:V1.2全吃掉,后续找冒号Colon时已经没内容了,所以报错"期望冒号但到达输入末尾"。

直接修改解析规则,让header和value的匹配范围精准对应冒号的前后部分即可:

void Main()
{
    string message = "accept-version:V1.2";
    StompFrame_Grammar.Parse_StompFrame(message).Dump();
}

public class StompFrame_Grammar
{
    public static Parser<char> Colon = Parse.Char(':').Token();

    // 匹配冒号之前的header名称:排除冒号字符
    public static Parser<string> HeaderText =
        Parse.CharExcept(':').Many().Text().Token();

    // 匹配冒号之后的value:任意字符直到输入结束
    public static Parser<string> ValueText =
        Parse.AnyChar.Many().Text().Token();

    public static Parser<Foo> StompFrame_Headers_Parser =
            from headerStr in HeaderText
            from colon in Colon
            from headerVal in ValueText
            select new Foo(headerStr, headerVal);

    public static Foo Parse_StompFrame(string frameContents)
    {
        return StompFrame_Headers_Parser.End().Parse(frameContents);
    }
}

public struct Foo
{
    public string Header { get; }
    public string Value { get; }

    public Foo(string hdr, string val)
    {
        Header = hdr;
        Value = val;
    }
}

关键改动说明:

  1. 拆分了原有的Text解析器,分别定义HeaderText和ValueText:
    • HeaderText用CharExcept(':')确保只捕获冒号前的header名称
    • ValueText用AnyChar.Many()捕获冒号后到结尾的所有内容(如果你的场景中value有其他终止规则,比如换行,可以替换成对应的排除规则)
  2. 给Foo结构体加了公开属性,方便查看解析结果(原代码的字段是私有,Dump()可能看不到内容)

修改后运行代码,就能正确提取accept-version和V1.2两个部分。

内容的提问来源于stack exchange,提问作者umbersar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:20:33