正则表达式(Rust)

课题

  1. 使用正则表达式匹配字符串
    使用正则表达式 "d{3}-(d{4})-d{2}" 匹配字符串 "123-4567-89"
    返回匹配结果:’"123-4567-89" 以及 "4567"
  2. 使用正则表达式替换字符串(模式)
    使用正则表达式 "(d+)-(d+)-(d+)" 匹配字符串 "123-4567-89"
    使用模式字符串 "$3-$1-$2" 替换匹配结果,返回结果 "89-123-4567"。
  3. 使用正则表达式替换字符串(回调)
    使用正则表达式 "d+" 匹配字符串 "123-4567-89"
    将匹配结果即三个数字串全部翻转过来,返回结果 "321-7654-98"。
  4. 使用正则表达式分割字符串
    使用正则表达式 "%(begin|next|end)%" 分割字符串"%begin%hello%next%world%end%"
    返回正则表达式分隔符之间的两个字符串 "hello" 和 "world"。

Rust

use regex::{Regex, Captures};
use std::ops::Index;
use itertools::Itertools;

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(())
}

/*
Found Matches:
group 0,0 : 123-4567-89
group 0,1 : 4567
group 1,0 : 987-6543-21
group 1,1 : 6543
89-123-4567,21-987-6543
321-7654-98,789-3456-12
["", "hello", "world", ""]
*/
原文地址:https://www.cnblogs.com/zwvista/p/12783743.html