ln.parse/ln.parse/tokenizer/RegularExpressionMatcher.cs

38 lines
1.3 KiB
C#
Raw Normal View History

2020-11-19 20:32:34 +01:00
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace ln.parse.tokenizer
{
public class RegularExpressionMatcher : TokenMatcher
{
Regex regex;
2020-11-24 18:17:58 +01:00
Func<SourceBuffer, int, int, string, Token> createTokenDelegate;
2020-11-19 20:32:34 +01:00
2020-11-24 18:17:58 +01:00
public RegularExpressionMatcher(string pattern,Func<SourceBuffer,int,int,string,Token> createTokenDelegate)
2020-11-19 20:32:34 +01:00
:this(pattern)
{
this.createTokenDelegate = createTokenDelegate;
}
protected RegularExpressionMatcher(string pattern)
{
2020-11-24 18:17:58 +01:00
regex = new Regex(pattern,RegexOptions.Singleline);
2020-11-19 20:32:34 +01:00
}
2020-11-24 18:17:58 +01:00
public virtual Token CreateToken(SourceBuffer sourceBuffer, int start, int length, string value) => createTokenDelegate(sourceBuffer, start, length, value);
2020-11-19 20:32:34 +01:00
public override bool Match(SourceBuffer sourceBuffer,out Token token)
{
Match match = regex.Match(sourceBuffer.GetCurrentText());
if ((match != null) && match.Success && (match.Index == 0))
{
2020-11-24 18:17:58 +01:00
token = CreateToken(sourceBuffer, sourceBuffer.LinearPosition, match.Length, match.Groups["value"].Value);
2020-11-19 20:32:34 +01:00
return true;
}
token = null;
return false;
}
}
}