regex_try 0.1.0

Replace methods for Regex propogating errors via Result.
Documentation
  • Coverage
  • 100%
    5 out of 5 items documented1 out of 5 items with examples
  • Size
  • Source code size: 5.66 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.37 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • xixixao

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