C++ 用正则表达式解析命令
有这样一种模式:C++ 用正则表达式解析命令,c++,regex,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_nam
(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”。混合使用这些命令的情况有三种:
- '解析'+'如果'
- “解析”
- “如果”
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;
}
这种情况下正确的正则表达式是什么?
你应该考虑使用一个实际的解析器而不是正则表达式。正则表达式是一个强大的工具,但您试图做的并不是它们真正的用途。要么自己编写(对手头的问题不那么难),要么去找解析库或分析器生成器。
你应该考虑使用一个实际的解析器而不是正则表达式。正则表达式是一个强大的工具,但您试图做的并不是它们真正的用途。要么自己写一个(对于手头的问题来说应该没那么难),要么去找一个解析库或解析器生成器。什么是无?空字符串是可接受的输入吗?这意味着命令是空的,但我认为在运行之前检查string.empty()更容易,我会更改它。为什么要使用正则表达式来执行此操作?听起来您想为您的命令构建一个词法分析器和解析器。你所要做的就是为你的语言描述一个合法的语法,自动化的工具可以为你生成一个词法分析器和解析器。看起来是这样。什么是没有?空字符串是可接受的输入吗?这意味着命令是空的,但我认为在运行之前检查string.empty()更容易,我会更改它。为什么要使用正则表达式来执行此操作?听起来您想为您的命令构建一个词法分析器和解析器。你所要做的就是为你的语言描述一个合法的语法,自动化的工具可以为你生成一个词法分析器和解析器。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