gpt4 book ai didi

c++ - spirit X3 : Rule that parses a single character and generates a string

转载 作者:行者123 更新时间:2023-12-04 13:25:34 25 4
gpt4 key购买 nike

是否可以在 Spirit X3 中创建一个解析单个字符并生成字符串的规则?

我想在版本号解析器的上下文中使用它,其中每个数字标识符可以是单个数字,也可以是非零数字后跟一个或多个数字:

auto const positive_digit = char_(L"123456789");
auto const digit = char_(L"0123456789");
auto const digits = x3::rule<class digits, std::wstring>{"digits"} = +digit;
auto const numeric_identifier = (positive_digit >> digits) | digit;

我看到的问题是 numeric_identifier 合成的类型与字符串不兼容(参见完整示例 here)。

为了解决这个问题,我需要创建一个匹配数字并合成字符串的规则。我能想到的唯一解决方案是使用语义操作,但是当在需要回溯的情况下使用规则时,这会导致错误(参见完整示例 here)。

最佳答案

我不太清楚你要做什么。如果目标是验证字符串的格式但解析与输入字符串完全匹配,为什么不使用 x3::raw

例如

auto num_id  = x3::uint_;
auto version = x3::raw[num_id % '.'];

现在可以直接将典型的版本字符串解析成字符串:

Live On Coliru

int main() {
for (sv input : {"0", "1", "1.4", "1.6.77.0.1234",}) {
std::string parsed;

std::cout << "Parsing " << std::quoted(input);

auto f = begin(input), l = end(input);

if (parse(f, l, version, parsed)) {
std::cout << " -> " << std::quoted(parsed) << "\n";
} else {
std::cout << " -- FAILED\n";
}

if (f != l) {
std::cout << "Remaining unparsed: " << std::quoted(sv{f, l}) << "\n";
}
}
}

打印

Parsing "0" -> "0"
Parsing "1" -> "1"
Parsing "1.4" -> "1.4"
Parsing "1.6.77.0.1234" -> "1.6.77.0.1234"

要添加 ID 号不能以 0 开头的限制,除非它们实际上是 0:

auto num_id  = x3::char_('0') | x3::uint_;

当然,你可以不那么聪明,也可以更直率:

auto num_id
= !x3::lit('0') >> x3::uint_
| x3::uint_parser<unsigned, 10, 1, 1>{};

效果是等价的。我更喜欢第一个。

关于c++ - spirit X3 : Rule that parses a single character and generates a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68852914/

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