Include array of strings in the possible patterns

Just like

filter(|string| string.contains(array of chars))

I want to use an array of strings instead of defining a separate function inside a map.

Sample code which I want:

filter(|string| string.contains(array of substrings))

Does it have to contain any of them or all of them? If all of them, in sequential order or not? Can they overlap?

any of them, not in sequential order, they can overlap, and if anyone is true it can return true. It is just that without calling the same thing multiple times, it can be called just once.

I would not raise this concern if the char array was not allowed. Apart from the overlapping part, the chars array already does all of this.

Would something like

filter(|string| substrings.iter().any(|substring| string.contains(substring)))


Searching for one of multiple possible substrings in a string simultaneously is not entirely trivial to do efficiently. You could use the aho-corasick crate for example.

Something like

use aho_corasick::AhoCorasick;
let ac = AhoCorasick::new_auto_configured(&(array of substrings));
[...].filter(|string| ac.is_match(string))

I know this. I am asking if it is possible to do this without preparing another iterator of substrings. Steffahn's solution is close to what I want to do although I would prefer if it could be done without any external crate.

Assuming that it can't be done without importing any crate, I am marking it as a valid answer.

Well it can be done, but probably not as efficiently. Aho_corasick runs in linear time (linear in the length of the string being searched), no matter how many substrings of what length you have. (Building the AhoCorasick object itself takes some time too, though, hence I assign it to a variable to be re-used multiple times in the call to filter.)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.