正则表达式是一种强大的文本处理工具。在 Rust 中,我们主要通过 regex crate 来使用正则表达式。让我们通过实际案例来学习。
1. 基础匹配 use regex::Regex; fn main() { // 创建正则表达式对象 let re = Regex::new(r"\d+").unwrap(); // 测试匹配 let text = "The year is 2024"; if re.is_match(text) { println!("Found a number!"); } // 提取匹配内容 if let Some(matched) = re.find(text) { println!("Found number: {}", matched.as_str()); } } 2. 处理重复单词 根据文章中提到的一个常见问题 - 查找重复单词:
use regex::Regex; fn remove_duplicate_words(text: &str) -> String { // (\w+) 捕获一个单词,\s+匹配空白字符,\1 回引用前面捕获的单词 let re = Regex::new(r"(\w+)\s+\1").unwrap(); re....
melody是一款rust编写的编译输出为正则表达式的语言。Arch用户可以使用 paru -Syu melody 来安装,vscode和jetbrains系的IDE也有插件。
语法 下面是基于官方book的机翻语法。
量词 ... of - 用于表达特定数量的模式。相当于正则表达式 {5} (假设 5 of ... ) ... to ... of - 用于表示模式范围内的数量。相当于正则表达式 {5,9} (假设 5 to 9 of ... ) over ... of - 用于表达多个模式。相当于正则表达式 {6,} (假设 over 5 of ... ) some of - 用于表达 1 个或多个模式。相当于正则表达式 + any of - 用于表达 0 个或多个模式。相当于正则表达式 * option of - 用于表示模式的 0 或 1。相当于正则表达式 ? 所有量词前面都可以添加 lazy 以匹配最少数量的字符而不是最多的字符(贪婪)。相当于正则表达式 +? 、 *?...
参考sdk定义
package main import ( "fmt" "regexp" ) // wechat pay 用户付款码条形码规则:18位纯数字,以10、11、12、13、14、15开头 // alipay 支付授权码,25~30开头的长度为16~24位的数字,实际字符串长度以开发者获取的付款码长度为准 func main() { // wechat regwechat:=regexp.MustCompile("^(1[0-5])\\d{16}$") matchwechat := regwechat.MatchString("154658833119096245") fmt.Println(matchwechat) // alipay regalipay:=regexp.MustCompile("^(2[5-9]|30)\\d{14,22}$") matchalipay := regalipay.MatchString("307573774583867517336") fmt.Println(matchalipay) } 参考
微信
支付宝