- Rust Standard Library Cookbook
- Jan Nils Ferner Daniel Durante
- 313字
- 2021-08-27 19:45:05
How to do it...
Open the Cargo.toml file that was generated earlier for you
- Under [dependencies], add the following line:
regex = "0.2"
- 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
In the bin folder, create a file called regex.rs
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:\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);
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:\t{}",
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 }
推薦閱讀
- SMT實(shí)用指南
- FTTx PON技術(shù)與應(yīng)用
- 密碼之謎
- 中壓電纜全壽命周期典型缺陷圖集
- 輕松學(xué)iPhone開發(fā)
- 通信線路工程設(shè)計(jì)、施工與維護(hù)(第2版)
- 電子產(chǎn)品零部件檢測(cè)與選用技能演練
- 光纜與光設(shè)備維護(hù)
- 嵌入式Linux網(wǎng)絡(luò)體系結(jié)構(gòu)設(shè)計(jì)與TCP/IP協(xié)議棧
- 數(shù)據(jù)虛擬化:多源異構(gòu)數(shù)據(jù)集成之道
- 電子工藝實(shí)習(xí)
- 現(xiàn)代電信名詞術(shù)語解釋(第二版)
- Cocos2d-x學(xué)習(xí)筆記:完全掌握C++ API與游戲項(xiàng)目開發(fā) (未來書庫)
- 高速信號(hào)傳輸工程化技術(shù):概念與方法
- 數(shù)字身份:在數(shù)字空間,如何安全地證明你是你