Ken*_*ntH 2 c++ boost-spirit c++11 boost-spirit-x3
如何防止 X3 符号解析器匹配部分标记?在下面的示例中,我想匹配“foo”,但不匹配“foobar”。我尝试将符号解析器放入指令中,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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
Qi 曾经distinct在他们的存储库中拥有。
X3没有。
解决您所展示的情况的方法是一个简单的前瞻断言:
auto r = lexeme [ sym >> !alnum ];
Run Code Online (Sandbox Code Playgroud)
您也可以distinct轻松制作一个助手,例如:
auto kw = [](auto p) { return lexeme [ p >> !(alnum | '_') ]; };
Run Code Online (Sandbox Code Playgroud)
现在你可以解析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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
印刷
Parsing 'foo': 1 Remaining: ''
Parsing 'foobar': Parse failed
Parsing 'barfoo': Parse failed
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
633 次 |
| 最近记录: |