string - 通过正则表达式拆分字符串以获得 Vec<String>

标签 string rust

我正在尝试拆分 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/

相关文章:

python - 有没有更有效的方法来扩展字符串?

ios - 如何在 swift 中每 N 个字符处为字符串添加分隔符?

generics - 如果我已经为 U 实现了 From<T>,Rust 是否为 Vec<U> 实现了 From<Vec<T>>?

rust - 有没有办法创建 std::slice::Iter 的类型别名?

floating-point - 如何处理 Rust 中不精确的浮点运算结果?

function - 定义将参数传递给函数的宏

string - 我如何在 swift 中创建一个新行

c# - 获取输入字符串的位置然后在两端获取子字符串

java - 如何将字符串拆分为数组,其中分隔符也是一个标记?

rust - 在 Rust 中的堆上创建一个固定大小的数组