111,128
社区成员
发帖
与我相关
我的任务
分享
funcname ::= Name {`.´ Name} [`:´ Name]
namelist ::= Name {`,´ Name}
prefixexp ::= var | functioncall | `(´ exp `)´
functioncall ::= prefixexp args | prefixexp `:´ Name args

public class RegexBuilder
{
private static Dictionary<string, string> tokenMap = new Dictionary<string, string>();
private static Regex tokenReg = new Regex(@"\{[a-zA-Z]+?\}");
public static void Build(BNF bnfData)
{
try
{
foreach (var item in bnfData.TokenList)
{
if (RegexBuilder.tokenMap.ContainsKey(item.Name))
{
DataException.Throw<Exception>("There is already an item exists with same name: {0}", item.Name);
}
RegexBuilder.tokenMap.Add(string.Format("{{{0}}}", item.Name), item.Value);
}
foreach (var item in bnfData.TokenList)
{
RegexBuilder.UpdateToken(item);
}
bnfData.TokenList.ForEach(item => item.BuildRegex());
tokenMap.Clear();
}
catch
{
throw;
}
}
private static void UpdateToken(Token token)
{
StringBuilder newToken = new StringBuilder();
MatchCollection matches = tokenReg.Matches(token.Value);
if (matches.Count > 0)
{
int lastMatchPos = 0;
foreach (Match match in matches)
{
string regexStr = match.Groups[0].Value;
newToken.Append(token.Value.Substring(lastMatchPos, match.Groups[0].Index - lastMatchPos));
lastMatchPos = match.Groups[0].Index + match.Groups[0].Length;
if (RegexBuilder.tokenMap.ContainsKey(regexStr))
{
newToken.Append(tokenMap[regexStr]);
}
else
{
DataException.Throw<Exception>("There is no token exists with name: {0}", token);
}
}
newToken.Append(token.Value.Substring(lastMatchPos));
token.Value = newToken.ToString();
RegexBuilder.UpdateToken(token);
}
}
}
