使用Boost Spirit识别并忽略双括号包裹字符串遇问题
解决Boost Spirit中忽略双层括号令牌的问题
你的问题出在当前的omit_string规则只能匹配单对括号包裹的内容,无法处理((sd-pam))这种双层括号的情况——原规则里的+(char_ - ')')会在遇到第一个右括号时就停止匹配,导致后续的右括号无法被规则捕获,最终匹配失败。
下面给出两种针对性的解决方案:
方案1:针对固定双层括号的场景
如果只需要处理((...))这种格式的令牌,直接修改omit_string规则,明确匹配首尾的双层括号:
omit_string %= lexeme["((" >> +(char_ - '))') >> "))"];
"(("精准匹配开头的两个左括号+(char_ - '))'匹配中间所有不以))结尾的内容"))"匹配结尾的两个右括号
这种写法简单直接,完全适配你当前的字符串格式。
方案2:支持任意深度嵌套括号的通用场景
如果后续需要处理更深层次的嵌套括号(比如(((sd-pam)))),可以用递归规则实现通用匹配:
#include <boost/spirit/include/qi.hpp> namespace qi = boost::spirit::qi; template<typename Iterator> struct YourGrammar : qi::grammar<Iterator> { YourGrammar() : YourGrammar::base_type(start) { // 递归规则:匹配嵌套括号内容 nested_content %= +(qi::char_ - '(' - ')' | '(' >> nested_content >> ')'); // 匹配任意一对括号包裹的内容(支持嵌套) omit_string %= qi::lexeme['(' >> nested_content >> ')']; start %= qi::int_ >> qi::omit[omit_string >> qi::char_ >> qi::repeat(10)[qi::long_]] >> qi::long_ >> qi::long_ >> qi::long_ >> qi::long_ ; } qi::rule<Iterator, std::string()> nested_content; qi::rule<Iterator> omit_string; qi::rule<Iterator> start; };
这里nested_content通过递归实现了对任意嵌套括号的匹配,不管括号层数多少,都能正确捕获从第一个左括号到对应闭合右括号的全部内容。
内容的提问来源于stack exchange,提问作者s488alex
相关产品推荐
相关产品推荐

