c# - 使用 Sprache 解析文本时,我可以确定原始字符串中的当前索引吗?

标签 c# parsing sprache

我设置了 Sprache 来解析一个方程,该方程中有许多不同的可能方法调用。解析方法后,有没有办法确定原始字符串中的索引值?也许解析有一个可以以某种方式访问​​的“当前索引”值和“长度”值?

输入字符串示例:

IndexOf("fred", 2) + IndexOf("bob")

使用这样的解析器...

Parser<Expression> FunctionCall = from namePart in Parse.Letter.Many().Text()
                       from lparen in Parse.Char('(')
                       from expr in Parameter.DelimitedBy(ListDelimiter)
                       from rparen in Parse.Char(')')
                       select CallMethod(namePart, Enumerable.Repeat(sourceData, 1)
                                                             .Concat(expr)
                                                             .ToArray());

谁能想到一个“技巧”,让我确定第一个 CallMethod 处理 SubString(0, 18),第二个 CallMethod 处理 SubString(21, 14) 来自原始字符串?

最佳答案

如果您使用通用类和扩展方法,您可以采用更通用的方法

public class PositionAware<T> : IPositionAware<PositionAware<T>>
{
    public PositionAware(T value)
    {
        Value = value;
    }

    public T Value { get; }
    public Position Start { get; private set; }
    public int Length { get; private set; }
    public PositionAware<T> SetPos(Position startPos, int length)
    {
        Start = startPos;
        Length = length;
        return this;
    }

}
public static Parser<PositionAware<T>> WithPosition<T>(this Parser<T> value)
{
    return value.Select(x => new PositionAware<T>(x)).Positioned();
}

使用它:

from c in Parse.Char('a').WithPosition()
select (c.Start, c.Value)

from c in Parameter.DelimitedBy(ListDelimiter).WithPosition()
select (c.Start, c.Value)

关于c# - 使用 Sprache 解析文本时,我可以确定原始字符串中的当前索引吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57120923/

相关文章:

c# - 调试一个简单的碰撞处理器

python - 我如何用 Python 解析 GeoJSON

sprache - 使用 Sprache 解析文件时出现异常 "Parsing failure: Unexpected end of input reached; expected ="

c# - 当表达式的开头相同时,如何使用 Sprache 解析表达式

c# - 使用 TryUpdateModel 方法在 ASP.NET MVC 3 中使用 EntityFramework 更新多个对象

c# - 我应该如何在后续的批处理任务之间传输文件?

c# - 当前上下文中不存在注册表单

javascript - 如何使用 native Angular 代码解析外部链接 url?

java - 使用 JSOUP 读取维基百科 "All Pages"特殊页面的标题

c# - 如何改进缺少右大括号的 Sprache 解析器错误消息?