gpt4 book ai didi

c++ - 使用正则表达式解析命令

转载 作者:行者123 更新时间:2023-11-28 01:03:22 25 4
gpt4 key购买 nike

有这样的模式:

(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'('==' or '!=')'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

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

最佳答案

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

关于c++ - 使用正则表达式解析命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7697176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com