我需要用我的.Net应用程序解析一个MDX。最初,我使用正则表达式来做这件事,但是表达式变得越来越复杂,一位正则表达式专家建议我使用解析器会更好。
有没有专门针对MDX的解析器?我尝试了Ranet,但由于某些未知的原因,它没有安装在我的机器上(没有显示任何错误消息)。
我需要将MDX的几个部分拆分为字符串。例如,一个字符串中的where子句,另一个字符串中的from子句等。
发布于 2011-10-16 03:14:20
最好的解决方案是找到一个解析器,但总是很难找到满足您特定需求的解析器。因此,如果您最终要编写解析器Ve parser是一个比正则表达式更好的工具,因为它提供了更多的解析功能,您可以生成更好的输出,而且由于您调用的是.net方法,因此它隐含地具有编写解析器的智能。缺点是它仍然没有很好的文档记录,因此您可能会发现在某些特殊情况下很难实现。
项目链接:http://veparser.codeplex.com
NuGet标识符: veparser
如果您需要获取MDX不同部分的文本,以下是部分示例代码:
using VeParser;
using System.Linq;
using System.Collections.Generic;
using System;
public class MDXParser : TokenParser
{
protected override Parser GetRootParser()
{
// read the following line as : fill 'select' property of 'current object(which is a statement)' with the 'new value of selectStatement' after facing a sequence of a select statement and then the symbol of ( and then a delemitied list of identierfiers filling the 'fileds' property of 'current selectStatement object' delemitied by ',' and finally expect the sequence to be finished with a symbol of ')'
var selectStatement = fill("select", create<selectStatment>( seq(expectKeyword_of("select"), expectSymbol_of("("), deleimitedList(expectSymbol_of(","), fill("fields",identifier) ), expectSymbol_of(")"))));
// read the following line as : fill the from property of 'current object(which is a statement)' with an expected identifier that is after a 'from' keyword
var fromStatement = seq(expectKeyword_of("from"), fill("from", identifier));
// the following statement is incomplete, as I just wanted to show a sample bit, If you are interested I can help you complete the parser until the full documentation become available.
var whereStatement = fill("where", create<whereStatement>(seq(expectKeyword_of("where"))));
var statement = create<statement>(seq(selectStatement, fromStatement, whereStatement));
return statement;
}
public statement Parse(string code)
{
var keywords = new[] { "select", "where", "from" };
var symbols = new[] { "(",")", ".", "[", "]" };
var tokenList = Lexer.Parser(code, keywords, symbols, ignoreWhireSpaces : true);
// Now we have our string input converted into a list of tokens which actually is a list of words but with some additional information about any word, for example a "select" is marked as keyword
var parseResult = base.Parse(tokenList.tokens);
if (parseResult == null)
throw new Exception("Invalid Code, at the moment Ve Parser does not support any error reporting feature.");
else
return (statement)parseResult;
}
}
public class statement
{
public selectStatment select;
public string where;
public identifier from;
}
public class selectStatment
{
public List<identifier> fields;
}
public class whereStatement
{
}
这段代码并不完整,我只是想演示如何使用Ve Parser为MDX编写自己的解析器。如果您喜欢这个库并想要使用它,我很乐意为您提供所需的所有描述和技术。
发布于 2011-10-10 07:33:03
您可以看看像http://grammatica.percederberg.net/这样的解析器生成器
尽管制定语法并使其跟上时代是一项艰巨的工作。
https://stackoverflow.com/questions/7709066
复制