正则表达式(Rust)
代码
use regex::{Regex, Captures}; use itertools::Itertools; use std::error::Error; fn main() -> Result<(), Box<dyn Error>> { let s = "123-4567-89,987-6543-21"; let r = Regex::new(r"\d{3}-(\d{4})-\d{2}")?; if r.is_match(s) { // if let m = r.find(s) { println!("Found Matches:") } for (i, c) in r.captures_iter(&s).enumerate() { for j in 0..c.len() { println!("group {},{} : {}", i, j, &c[j]); } } let r2 = Regex::new(r"(\d+)-(\d+)-(\d+)")?; let s2 = r2.replace_all(&s, "$3-$1-$2"); println!("{}", s2); let r3 = Regex::new(r"\d+")?; let s3 = r3.replace_all(&s, |c: &Captures| c[0].chars().rev().collect::<String>()); println!("{}", s3); let r4 = Regex::new("%(begin|next|end)%")?; let s4 = "%begin%hello%next%world%end%"; let v = r4.split(s4).collect_vec(); println!("{:?}", v); Ok(()) }
Cargo.toml:
[dependencies]
itertools = "0.10.1"
regex ="1.5.4"
可以根据错误提示在crates.io中查找依赖
正则语法:https://docs.rs/regex/1.5.4/regex/#syntax
参考 :https://www.cnblogs.com/zwvista/p/12783743.html
https://blog.csdn.net/wsp_1138886114/article/details/116519242