首页 > 其他 > 详细

正则表达式(Rust)

时间:2020-04-27 01:04:37      阅读:443      评论:0      收藏:0      [点我收藏+]

课题

  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() {
    let s = "123-4567-89,987-6543-21";
    let r = Regex::new(r"\d{3}-(\d{4})-\d{2}").unwrap();
    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+)").unwrap();
    let s2 = r2.replace_all(&s, "$3-$1-$2");
    println!("{}", s2);

    let r3 = Regex::new(r"\d+").unwrap();
    let s3 = r3.replace_all(&s, |c: &Captures| c[0].chars().rev().collect::<String>());
    println!("{}", s3);

    let r4 = Regex::new(r"%(begin|next|end)%").unwrap();
    let s4 = "%begin%hello%next%world%end%";
    let v = r4.split(s4).collect_vec();
    println!("{:?}", v);
}

/*
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", ""]
*/

正则表达式(Rust)

原文:https://www.cnblogs.com/zwvista/p/12783743.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!