如何在Rust中计算正则表达式匹配数?

tlo*_*tlo 3 regex rust

我想用Rust计数字符串中正则表达式的匹配项。我设法打印了所有匹配项:

let re = Regex::new(r"(?i)foo").unwrap();
let result = re.find_iter("This is foo and FOO foo as well as FoO.");
for i in result {
    println!("{}", i.as_str())
}
Run Code Online (Sandbox Code Playgroud)

但是我不能简单地得出比赛的次数。我找不到任何可以计数的函数。我也尝试过size_hint(),但是效果不佳。有什么办法可以做到吗?

是我正在寻找的Scala版本。

Bur*_*hi5 6

您已经有了迭代器,因此只需计算迭代器中的元素数即可:

re.find_iter("This is foo and FOO foo as well as FoO.").count()
Run Code Online (Sandbox Code Playgroud)

  • 我现在有点尴尬...非常感谢! (2认同)