Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String by Regex to get Vec<String>

Tags:

string

rust

I'm trying to split an std::string::String using regex::Regex and get a Vec<String>. The minimal code looks as follows:

let words: Vec<String> = Regex::new(r"\W+")
    .unwrap()
    .split(&file_raw.to_owned())
    .collect()
    .map(|x| x.to_string());

On the last line I'm getting an error: method not found in 'std::vec::Vec<&str>' with a note:

the method `map` exists but the following trait bounds were not satisfied:
`std::vec::Vec<&str>: std::iter::Iterator`
which is required by `&mut std::vec::Vec<&str>: std::iter::Iterator`
`[&str]: std::iter::Iterator`
which is required by `&mut [&str]: std::iter::Iterator`

This question bears strong resemblance to this one, but the offered solution is exactly the one I tried and fails. I'd be grateful if someone could explain the type difference between splitting by String::split member function and Regex::split.

like image 426
Vilda Avatar asked Oct 19 '25 05:10

Vilda


1 Answers

Your .collect() returns a Vec which is not an iterator. You could of course obtain an iterator from Vec with .iter() and then apply .map() but I suspect what you really want is to .map() before you .collect():

let words: Vec<String> = Regex::new(r"\W+")
    .unwrap()
    .split(&file_raw.to_owned())
    .map(|x| x.to_string())
    .collect();
like image 167
eggyal Avatar answered Oct 21 '25 23:10

eggyal