使用正则表达式解析命令
Parsing commands with regular expression
有这样的模式:
(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
对于这种情况,正确的正则表达式是什么?
您应该考虑使用实际的解析器而不是正则表达式。正则表达式是一个强大的工具,但是您要做的并不是它们真正的目的。您可以自己编写一个(对于手头的问题应该不会太难),或者去寻找解析库或解析器生成器。
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++正则表达式无限循环
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 带有多个字符分隔符的正则表达式
- C++ 使用增强正则表达式库时断言崩溃
- 有人可以帮助我处理正则表达式吗?
- 使用正则表达式获取大括号块的列表
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 组合正则表达式部分使用 | 不起作用的 C++
- 为什么C++正则表达式这么慢?
- 如何使HTML5电子邮件验证正则表达式在C++中工作?
- 在C++中实现正则表达式
- C++正则表达式替换整个单词
- 用C++编写正则表达式的正确方法是什么?
- 如何从Stroustrup的C++书中解释这个正则表达式?
- 为什么这个正则表达式C++在括号表达式中抛出无效范围异常?
- 使用正则表达式和 sed 命令替换C++代码中的' *'指针不起作用
- 使用正则表达式解析命令