我设置了 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/