> V; -6ren">
gpt4 book ai didi

c++ - 语法问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:46:30 25 4
gpt4 key购买 nike

我需要解析一个表达式并且我正在使用 boost::spirit,该表达式必须具有以下形式(@除@之外的任何内容都跟在字符串 .PV@ 之后),我正在使用以下语法

P = S >> "." >> V;

S = ch_p('@') >> +~ch_p('@');

V = str_p(".PV@");

但是对我不起作用,你能告诉我错误在哪里吗?我需要用语法来做,我正在使用命名空间 boost::spirit

最佳答案

更新 为了完整添加正则表达式方法(见底部)

本着 V2 的精神,我建议更简单

    P = S >> V;
S = '@' >> +(char_ - '@' - V);
V = ".PV@";

假设您的意思不是需要双 .。看一个测试程序 Live On Coliru .

另外,请注意 spirit 存储库中的 confix 解析器,它可以更简洁地完成此操作:

confix('@', ".PV@")[+(char_ - '@' - ".PV@")]

看到那个 Live On Coliru 也是。

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/repository/include/qi_confix.hpp>

namespace qi = boost::spirit::qi;
using boost::spirit::repository::confix;

int main()
{
std::string const input("@anything but &at; followed of the string .PV@");
std::string parsed;

auto f(input.begin()), l(input.end());
bool ok = qi::parse(
f, l,
confix('@', ".PV@") [+(qi::char_ - '@' - ".PV@")],
parsed);

if (ok) std::cout << "parse success\ndata: " << parsed << "\n";
else std::cerr << "parse failed: '" << std::string(f,l) << "'\n";
if (f!=l) std::cerr << "trailing unparsed: '" << std::string(f,l) << "'\n";

return ok? 0 : 255;
}

输出:

parse success
data: anything but &at; followed of the string

正则表达式方法

根据您的用例,您可以使用评论中指出的正则表达式。看一个简单的演示 Live On Coliru

#include <boost/regex.hpp>
using boost::regex;

int main()
{
std::string const input("@anything but &at; followed of the string .PV@");

boost::smatch matches;
if(regex_search(input, matches, regex("@(.*?)\\.PV@")))
std::cout << "Parse success, match string: '" << matches[1] << "'\n";
}

请记住,

  • Boost Regex 只是 header ,因此如果您还没有使用它,就会招致库依赖
  • std::regex 在我所知道的任何编译器/平台上准备就绪

关于c++ - 语法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21365433/

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