23 lines
965 B
C#
23 lines
965 B
C#
|
using CanonSharp.Combinator.Abstractions;
|
||
|
using CanonSharp.Combinator.Extensions;
|
||
|
using CanonSharp.Combinator.Parsers;
|
||
|
|
||
|
namespace CanonSharp.Combinator.Text;
|
||
|
|
||
|
/// <summary>
|
||
|
/// 字符串解析器
|
||
|
/// </summary>
|
||
|
/// <param name="except">期望的字符串</param>
|
||
|
/// <param name="comparison">字符串比较模式</param>
|
||
|
public class StringParser(string except, StringComparison comparison) : PrimitiveParser<char, string>
|
||
|
{
|
||
|
protected override ParseResult<char, string> Run<TState>(TState state)
|
||
|
{
|
||
|
TState[] states = state.AsEnumerable<char, TState>().Take(except.Length).ToArray();
|
||
|
string actual = new(states.Select(x => x.Current).ToArray());
|
||
|
return string.Equals(except, actual, comparison)
|
||
|
? ParseResultBuilder.Succeed<char, TState, string>(actual, states.Length == 0 ? state : states.Last().Next)
|
||
|
: ParseResultBuilder.Fail<char, TState, string>($"Except '{except}' but found '{actual}.", state);
|
||
|
}
|
||
|
}
|