#regex #result #try #supporting #replace #methods #error

regex_try

Replace methods for Regex propogating errors via Result

1 unstable release

0.1.0 Mar 1, 2021

#52 in #try

MIT/Apache

5KB

An extension of Regex supporting Result in replace methods.

The replace, replace_all and replacen methods of Regex accept a function returning the replacement for each matched substring, but they do not allow this function to return a Result. This crate provides try_replace, try_replace_all, and try_replacen which fill this gap.

Use

Include use regex_try::RegexTry to use the additional methods provided by this crate.

Example

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(())
}

Dependencies

~2.2–3MB
~55K SLoC