3 个版本
| 0.1.2 | 2024 年 2 月 17 日 |
|---|---|
| 0.1.1 | 2022 年 9 月 19 日 |
| 0.1.0 | 2022 年 9 月 17 日 |
#280 在 过程宏 中
14KB
339 行
str-match
类似于 format! 的匹配字符串模式。
使用方法
use str_match::str_match;
fn f(a: &str) -> &str{
str_match! {
match a {
"abc{a}ghi" => a,
"aaa{bb}" => bb,
"{{{x}}}" => x,
_ => "!",
}
}
}
assert_eq!(f("abcdefghi"), "def");
assert_eq!(f("aaabbbccc"), "bbbccc");
assert_eq!(f("{000}"), "000");
assert_eq!(f("xyz"), "!");
在 nightly 版本中,你可以使用 "attribute" 功能。
// with `str-match.features = ["attribute"]` in Cargo.toml
#![feature(stmt_expr_attributes, proc_macro_hygiene)]
use str_match::str_match;
fn f(a: &str) -> &str{
#[str_match]
match a {
"abc{x}ghi" => x,
"aaa{x}" => x,
"{{{x}}}" => x,
_ => "!",
}
}
限制
此宏将 &str 转换为 &[u8] 并使用匹配切片模式。例如,"abc{x}ghi" 模式转换为 [b'a', b'b', b'c', x @ .., b'g', b'h', b'i' ]。因为切片模式不允许有两个或多个可变参数模式,所以字符串模式也只允许有零个或一个占位符。
此宏可以使用单个 &str 匹配,不支持复杂模式(如 (&str, &str))。
依赖项
~275–730KB
~17K SLoC