Advertisement
Guest User

Untitled

a guest
Jun 4th, 2025
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.96 KB | None | 0 0
  1. // Ref https://old.reddit.com/r/programming/comments/1l2h781/on_no_syntactic_support_for_error_handling/mvy5zrd/
  2. use regex::Regex;
  3.  
  4. fn main() {
  5.     println!("{}", foo("123"));
  6.     println!("{}", bar("123").unwrap_or(0));
  7.     println!("{}", baz("123").unwrap_or(0));
  8. }
  9.  
  10. fn foo(input: &str) -> isize {
  11.     let p = Regex::new(r"-c(\d{1,3})")
  12.         .expect("We should have written a valid regex. This is a bug in the application.");
  13.  
  14.     p.captures(input)
  15.         .and_then(|captures| captures.get(1))
  16.         .and_then(|m| m.as_str().parse().ok())
  17.         .unwrap_or(0)
  18. }
  19.  
  20. fn bar(input: &str) -> Option<isize> {
  21.     let p = Regex::new(r"-c(\d{1,3})").ok()?;
  22.  
  23.     let captures = p.captures(input)?;
  24.     let matches = captures.get(1)?;
  25.     matches.as_str().parse().ok()
  26. }
  27.  
  28. fn baz(input: &str) -> Option<isize> {
  29.     Regex::new(r"-c(\d{1,3})")
  30.         .ok()?
  31.         .captures(input)?
  32.         .get(1)?
  33.         .as_str()
  34.         .parse()
  35.         .ok()
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement