1 个不稳定版本
| 0.1.0 | 2021 年 3 月 1 日 |
|---|
#57 in #try
5KB
Regex 的扩展,支持在 replace 方法中使用 Result。
replace、replace_all 和 replacen 方法接受一个函数,该函数返回每个匹配子字符串的替换内容,但它们不允许该函数返回 Result。此 crate 提供了 try_replace、try_replace_all 和 try_replacen,以填补这一空白。
使用
使用 use regex_try::RegexTry 来使用此 crate 提供的额外方法。
示例
use regex::Regex;
use regex_try::RegexTry;
pub fn main() -> Result<(), std::io::Error> {
let re = Regex::new(r"load! (\w+);").unwrap();
let template = std::fs::read_to_string("Cargo.toml")?;
let result = re.try_replace_all(&template, |captures|
// read_to_string returns a Result, and so it couldn't
// be used with re.replace_all
std::fs::read_to_string(&captures[1])
)?;
println!("{}", result);
Ok(())
}
依赖项
~2–3MB
~53K SLoC