add regex

This commit is contained in:
2020-01-30 21:05:01 +08:00
parent 447e8cf673
commit 62f7aad67b
2 changed files with 40 additions and 0 deletions

13
regex/Cargo.toml Normal file
View File

@@ -0,0 +1,13 @@
[package]
name = "regex"
version = "0.1.0"
authors = ["Hatter Jiang <jht5945@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
regex = "1.3.1"

27
regex/src/main.rs Normal file
View File

@@ -0,0 +1,27 @@
use regex::Regex;
const TO_SEARCH: &str = "
On 2010-03-14, foo happened. On 2014-10-14, bar happened.
";
fn main() {
let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
for caps in re.captures_iter(TO_SEARCH) {
println!("year: {}, month: {}, day: {}",
caps.get(1).unwrap().as_str(),
caps.get(2).unwrap().as_str(),
caps.get(3).unwrap().as_str());
}
let re2 = Regex::new(r"(\d+)").unwrap();
println!("{}", re2.replace_all("Hello 100, 200", | caps: &regex::Captures | {
"(".to_owned() + &caps[1] + ")"
}));
println!("{}", re2.replace_all("Hello 100, 200", | caps: &regex::Captures<'_> | {
"[".to_owned() + &caps[1] + "]"
}));
let re3 = Regex::new(r"(?P<x>\d+)").unwrap();
println!("{}", re3.replace_all("Hello 100, 200", "<$x>"));
}