tlo
tlo

Reputation: 1631

How to count regex matches in Rust?

I'd like to count the matches of a regex in a string with Rust. I managed to print all matches:

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())
}

But I fail to simply get the number of matches. I can't find any function that gives me the count. I also tried size_hint(), but that does not work as well. Any way I can do that?

Here is the Scala version of what I'm looking for.

Upvotes: 11

Views: 2590

Answers (1)

BurntSushi5
BurntSushi5

Reputation: 15354

You already have the iterator, so just count the number of elements in the iterator:

re.find_iter("This is foo and FOO foo as well as FoO.").count()

Upvotes: 15

Related Questions