add regex
This commit is contained in:
13
regex/Cargo.toml
Normal file
13
regex/Cargo.toml
Normal 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
27
regex/src/main.rs
Normal 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: ®ex::Captures | {
|
||||
"(".to_owned() + &caps[1] + ")"
|
||||
}));
|
||||
println!("{}", re2.replace_all("Hello 100, 200", | caps: ®ex::Captures<'_> | {
|
||||
"[".to_owned() + &caps[1] + "]"
|
||||
}));
|
||||
|
||||
let re3 = Regex::new(r"(?P<x>\d+)").unwrap();
|
||||
println!("{}", re3.replace_all("Hello 100, 200", "<$x>"));
|
||||
}
|
||||
Reference in New Issue
Block a user