使用正则表达式解析命令

时间:2011-10-08 13:39:13

标签: c++ regex

有这样的模式:

(parse file_name (txt or ini)) or/and (if (string)(== or !=)(string)/* must be at least one */ (and)/*cannot be at the end without expression on right*/)

说明:有两个命令 - 'parse'和'if'。混合这些命令有三种情况:

  • '解析'+'如果'
  • '解析'
  • '如果'

如果使用'parse',则必须提供'file_name',并且可以提供'txt'或'ini',但不必提供。

如果使用'if',则必须至少有一个操作'string'('=='或'!=')'string'。可以使用多个以'和'分隔的操作,但是'和'不能在操作列表的末尾使用,例如'如果a == c和b == d和' - 不正确。

我尝试编写以下正则表达式,但它不起作用:

std::string text = "parse file txt if hello==name and a!=age and owner==me";
boost::regex expr(".*(parse) *(\\w*) *(txt|ini)* *(if) *( *([a-z\"]+)(==|!=)([a-z\"]+) *(and)*)* *");
boost::smatch what;
std::cout << text << std::endl;
if (boost::regex_search(text, what, expr))
    for (int j = 0; j < what.size(); ++j)
    {
        std::cout << what[j] << std::endl;
    }

输出:

parse file txt if hello==name and a!=age and owner==me
parse file txt if hello==name and a!=age and 
parse
file
txt
if
 owner==me
owner
==
me
and

这种情况下正确的正则表达式是什么?

1 个答案:

答案 0 :(得分:3)

您应该考虑使用实际的解析器而不是正则表达式。正则表达式是一个强大的工具,但你想要做的并不是它们的真正含义。要么自己写一个(对于手头的问题不应该那么难),要么去寻找解析库或解析器生成器。

相关问题