Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count regex matches in Rust?

Tags:

regex

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.

like image 206
tlo Avatar asked Aug 31 '19 19:08

tlo


People also ask

Can you count with regex?

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.

Does rust have regex?

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.


Video Answer


1 Answers

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()
like image 183
BurntSushi5 Avatar answered Sep 18 '22 16:09

BurntSushi5