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.
To count a regex pattern multiple times in a given string, use the method len(re. findall(pattern, string)) that returns the number of matching substrings or len([*re. finditer(pattern, text)]) that unpacks all matching substrings into a list and returns the length of it as well.
A Rust library for parsing, compiling, and executing regular expressions. Its syntax is similar to Perl-style regular expressions, but lacks a few features like look around and backreferences. In exchange, all searches execute in linear time with respect to the size of the regular expression and search text.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With