正則表達式(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", ""]
*/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM