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 crates.io page (https://crates.io/crates/regex) to check for the newest version and use that one instead
  2. In the bin folder, create a file called regex.rs

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

1   extern crate regex;
2
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 =
Regex::new(r"^d{2}.d{2}.d{4}$").expect("Failed
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);
12
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],
&cap[1]);
21 }
22 // Replace the date format
23 println!("Original text: {}", text_with_dates);
24 let text_with_indian_dates =
date_regex.replace_all(text_with_dates, "$1-$2-$3");
25 println!("In indian format: {}", text_with_indian_dates);
26
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})
.(?P<year>d{4})")
30 .expect("Failed to create regex");
31 let text_with_american_dates =
date_regex.replace_all(text_with_dates,
"$month/$day/$year");
32 println!("In american format: {}",
text_with_american_dates);
33 let rust_regex = Regex::new(r"(?i)rust").expect("Failed to
create regex");
34 println!("Do we match RuSt? {}",
rust_regex.is_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? {}",
rust_regex.is_match("RuSt"));
41 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.60.63