匹配多个字符的最佳方式是什么



我有一个字符串列表,第一个只包含一个*,第二个包含两个*,而第三个包含一颗星和两颗星。我正在使用conatins函数来查找匹配项,但如果条件出现问题。我犯了什么错误,解决这个问题的最佳方法是什么。

链接到代码https://play.rust-lang.org/?version=stable&mode=调试&edition=2021&gist=89d53c620b58e61b60966d8c12aa7393

代码:

let mut list_str:Vec<&str> = Vec::new();
list_str.push("I only contains one *");
list_str.push("I contain two stars **");
list_str.push("I conatain single star * and two stars **");
for filter in list_str{
if filter.contains("*") && filter.contains("**"){
println!("String contains multiple stars >>: {} ",filter);
} 
else if filter.contains("**"){
println!("String contains two stars >>: {}",filter);
}
else if filter.contains("*"){
println!("String contains only one star  >>: {}",filter);
}
else{ 
continue;
}
}

使用子字符串搜索(Rust操场(

如果你不想使用RegEx,你可以这样做。也许它可以写得更有效率,但这应该让你知道它的意图是什么。

fn main() {
let mut list_str:Vec<&str> = Vec::new();
list_str.push("I only contains one *");
list_str.push("I contain two stars **");
list_str.push("I conatain single star * and two stars **");
for filter in list_str{
if let Some(i) = filter.find("*") {
if let Some(_) = filter.find("**") {
if filter[i+2..].contains("*") {
println!("String contains multiple stars >>: {} ",filter);
} else {
println!("String contains two stars >>: {}",filter);
}
} else {
println!("String contains only one star  >>: {}",filter);
}
} else { 
continue;
}
}
}

使用RegEx(Rust游乐场(

我可能更喜欢这种方法。简单、高效且可读性更强。请注意,if语句的顺序很重要(从最大匹配到最小匹配(。

use regex::Regex;
fn main() {
let mut list_str:Vec<&str> = Vec::new();
list_str.push("I only contains one *");
list_str.push("I contain two stars **");
list_str.push("I conatain single star * and two stars **");
let re1 = Regex::new(r"*").unwrap();
let re2 = Regex::new(r"**").unwrap();
let re12 = Regex::new(r"(*[^*]+**)|(**[^*]+*)").unwrap();
for filter in list_str{
if re12.is_match(filter) {
println!("String contains multiple stars >>: {} ",filter);
} else if re2.is_match(filter) {
println!("String contains two stars >>: {}",filter);
} else if re1.is_match(filter) {
println!("String contains only one star  >>: {}",filter);
} else { 
continue;
}
}
}

最新更新