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

what is the best way to match multiple characters

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

link 进行编码 https://play.rust-lang.org/?version=stable&mode=debug&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 playground)

如果你不想使用正则表达式,你可以这样做。可能它可以写得更有效,但这应该让您了解意图是什么。

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;
        }
    }
}

使用正则表达式 (Rust playground)

我可能更喜欢这种方法。简单,相当高效且更具可读性。 请注意,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;
        }
    }
}