Book Image

Rust Standard Library Cookbook

By : Jan Hohenheim, Daniel Durante
Book Image

Rust Standard Library Cookbook

By: Jan Hohenheim, Daniel Durante

Overview of this book

Mozilla’s Rust is gaining much attention with amazing features and a powerful library. This book will take you through varied recipes to teach you how to leverage the Standard library to implement efficient solutions. The book begins with a brief look at the basic modules of the Standard library and collections. From here, the recipes will cover packages that support file/directory handling and interaction through parsing. You will learn about packages related to advanced data structures, error handling, and networking. You will also learn to work with futures and experimental nightly features. The book also covers the most relevant external crates in Rust. By the end of the book, you will be proficient at using the Rust Standard library.
Table of Contents (12 chapters)

How to do it...

  1. Open the Cargo.toml file that was generated earlier for you

  2. Under [dependencies], add the following line:
regex = "0.2"
  1. If you want, you can go to regex's page ( to check for the newest version and use that one instead
  2. In the bin folder, create a file called

  3. Add the following code and run it with cargo run --bin regex:

1   extern crate regex;
3 fn main() {
4 use regex::Regex;
5 // Beginning a string with 'r' makes it a raw string,
6 // in which you don't need to escape any symbols
7 let date_regex =
to create regex");
8 let date = "15.10.2017";
9 // Check for a match
10 let is_date = date_regex.is_match(date);
11 println!("Is '{}' a date? {}", date, is_date);
13 // Let's use capture groups now
14 let date_regex = Regex::new(r"(\d{2}).(\d{2})
.(\d{4})").expect("Failed to create regex");
15 let text_with_dates = "Alan Turing was born on 23.06.1912 and
died on 07.06.1954. \
16 A movie about his life called 'The Imitation Game' came out
on 14.11.2017";
17 // Iterate over the matches
18 for cap in date_regex.captures_iter(text_with_dates) {
19 println!("Found date {}", &cap[0]);
20 println!("Year: {} Month: {} Day: {}", &cap[3], &cap[2],
21 }
22 // Replace the date format
23 println!("Original text:\t\t{}", text_with_dates);
24 let text_with_indian_dates =
date_regex.replace_all(text_with_dates, "$1-$2-$3");
25 println!("In indian format:\t{}", text_with_indian_dates);
27 // Replacing groups is easier when we name them
28 // ?P<somename> gives a capture group a name
29 let date_regex = Regex::new(r"(?P<day>\d{2}).(?P<month>\d{2})
30 .expect("Failed to create regex");
31 let text_with_american_dates =
32 println!("In american format:\t{}",
33 let rust_regex = Regex::new(r"(?i)rust").expect("Failed to
create regex");
34 println!("Do we match RuSt? {}",
35 use regex::RegexBuilder;
36 let rust_regex = RegexBuilder::new(r"rust")
37 .case_insensitive(true)
38 .build()
39 .expect("Failed to create regex");
40 println!("Do we still match RuSt? {}",
41 }