我正在尝试拆分 std::string::String
使用 regex::Regex
并获得 Vec<String>
.最小代码如下:
let words: Vec<String> = Regex::new(r"\W+")
.unwrap()
.split(&file_raw.to_owned())
.collect()
.map(|x| x.to_string());
在最后一行我收到一个错误:method not found in 'std::vec::Vec<&str>'
附注:
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 one 非常相似。 ,但提供的解决方案正是我尝试过但失败的解决方案。如果有人能解释 String::split
之间的类型差异,我将不胜感激成员函数和Regex::split
.
最佳答案
您的 .collect()
返回一个不是迭代器的 Vec
。您当然可以使用 .iter()
从 Vec
获取迭代器,然后应用 .map()
但我怀疑您真正想要的是到 .map()
你之前 .collect()
:
let words: Vec<String> = Regex::new(r"\W+")
.unwrap()
.split(&file_raw.to_owned())
.map(|x| x.to_string())
.collect();
关于string - 通过正则表达式拆分字符串以获得 Vec<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63338801/