使用正则表达式解析命令

Parsing commands with regular expression

本文关键字:命令 正则表达式      更新时间:2023-10-16

有这样的模式:

(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' + 'if'
  • "解析"
  • "如果"

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

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

我试着写下面的正则表达式,但它不工作:

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

对于这种情况,正确的正则表达式是什么?

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