C++ 停止匹配子字符串中的X3符号
如何防止X3符号解析器匹配部分标记?在下面的示例中,我希望匹配“foo”,但不匹配“foobar”。我尝试将符号解析器放入C++ 停止匹配子字符串中的X3符号,c++,c++11,boost-spirit,boost-spirit-x3,C++,C++11,Boost Spirit,Boost Spirit X3,如何防止X3符号解析器匹配部分标记?在下面的示例中,我希望匹配“foo”,但不匹配“foobar”。我尝试将符号解析器放入lexeme指令中,就像对待标识符一样,但没有任何匹配项 谢谢你的见解 #include <string> #include <iostream> #include <iomanip> #include <boost/spirit/home/x3.hpp> int main() { boost::spirit::x3
lexeme
指令中,就像对待标识符一样,但没有任何匹配项
谢谢你的见解
#include <string>
#include <iostream>
#include <iomanip>
#include <boost/spirit/home/x3.hpp>
int main() {
boost::spirit::x3::symbols<int> sym;
sym.add("foo", 1);
for (std::string const input : {
"foo",
"foobar",
"barfoo"
})
{
using namespace boost::spirit::x3;
std::cout << "\nParsing " << std::left << std::setw(20) << ("'" + input + "':");
int v;
auto iter = input.begin();
auto end = input.end();
bool ok;
{
// what's right rule??
// this matches nothing
// auto r = lexeme[sym - alnum];
// this matchs prefix strings
auto r = sym;
ok = phrase_parse(iter, end, r, space, v);
}
if (ok) {
std::cout << v << " Remaining: " << std::string(iter, end);
} else {
std::cout << "Parse failed";
}
}
}
#包括
#包括
#包括
#包括
int main(){
boost::spirit::x3::sym符号;
符号添加(“foo”,1);
对于(标准::字符串常量输入:{
“福”,
“foobar”,
“巴福”
})
{
使用名称空间boost::spirit::x3;
std::coutQi过去在他们的存储库中有distinct
X3没有
对于您展示的案例,解决这个问题的方法是一个简单的前瞻性断言:
auto r = lexeme [ sym >> !alnum ];
您也可以轻松创建一个不同的
帮助程序,例如:
auto kw = [](auto p) { return lexeme [ p >> !(alnum | '_') ]; };
现在您可以只解析kw(sym)
#include <iostream>
#include <boost/spirit/home/x3.hpp>
int main() {
boost::spirit::x3::symbols<int> sym;
sym.add("foo", 1);
for (std::string const input : { "foo", "foobar", "barfoo" }) {
std::cout << "\nParsing '" << input << "': ";
auto iter = input.begin();
auto const end = input.end();
int v = -1;
bool ok;
{
using namespace boost::spirit::x3;
auto kw = [](auto p) { return lexeme [ p >> !(alnum | '_') ]; };
ok = phrase_parse(iter, end, kw(sym), space, v);
}
if (ok) {
std::cout << v << " Remaining: '" << std::string(iter, end) << "'\n";
} else {
std::cout << "Parse failed";
}
}
}
非常感谢。我非常接近-“-”解析器在解析字符时工作。需要重新阅读(有限的)文档以获得前瞻性解析器。lambda帮助函数的额外功能!
Parsing 'foo': 1 Remaining: ''
Parsing 'foobar': Parse failed
Parsing 'barfoo': Parse failed