4 个稳定版本
1.3.0 | 2023年5月24日 |
---|---|
1.2.1 | 2022年11月15日 |
1.1.2 | 2021年10月24日 |
1.0.1 |
|
#949 in 解析实现
45 每月下载次数
12KB
145 行
eyes
使用可读模板解析和转换字符串。
该包的主要目的是解析 Advent of Code 挑战中的输入。它目前提供有限的功能,但可能会添加更多选项,前提是它们对解析稍微复杂一些的格式是有用的。
由于我希望保持其简单和轻量级的设计,因此该包没有任何依赖。
语法
模板中唯一的特殊字符是大括号 ('{}')。它们用作输入字符串中提取值的占位符。
示例
use eyes::parse;
let input = "#lol @ 338,7643: 20.2x24.5";
let template = "#{} @ {},{}: {}x{}";
let (id, x, y, w, h) = parse!(input, template, String, isize, isize, f64, f64);
assert_eq!((id.as_str(), x, y, w, h), ("lol", 338, 7643, 20.2, 24.5));
eyes 会贪婪地匹配捕获组,尽可能多地展开它们,因此以下示例也按预期工作
use eyes::parse;
let input = "turn off 660,55 through 986,197";
let template = "{} {},{} through {},{}";
let (op, x1, y1, x2, y2) = parse!(input, template, String, usize, usize, usize, usize);
assert_eq!(
(op.as_str(), x1, y1, x2, y2),
("turn off", 660, 55, 986, 197)
);
请注意,“关闭”被正确捕获,即使它包含空格。
对于错误处理,提供了 try_parse
宏,它可以在解析可能损坏的输入时非常有用
use eyes::try_parse;
let input = "1 2\n3,4\n5 6";
let result = input
.lines()
.filter_map(|line| try_parse!(line, "{} {}", i64, i64))
.collect::<Vec<_>>();
assert_eq!(vec![(1, 2), (5, 6)], result);