无法使用正则表达式提取单词:没有方法to_string匹配

joy*_*jee 1 regex rust

我试图循环一个句子并使用正则表达式获取单词:

use regex::Regex; // 1.0.6

fn example() {
    let re = Regex::new(r"\w+").unwrap();
    let sample_text = "This is me me.";
    for caps in re.captures_iter(&sample_text) {
        if let Some(cap) = caps.get(0) {
            let word = cap.to_string();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误.

error[E0599]: no method named `to_string` found for type `regex::re_unicode::Match<'_>` in the current scope
 --> src/lib.rs:8:28
  |
8 |             let word = cap.to_string();
  |                            ^^^^^^^^^
  |
  = note: the method `to_string` exists but the following trait bounds were not satisfied:
          `regex::re_unicode::Match<'_> : std::string::ToString`
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Web*_*rix 5

要获得&strMatch您可以使用此:

let my_str = cap.as_str(); // returns &str
Run Code Online (Sandbox Code Playgroud)

如果你真的想要一个String,你可以打电话to_string():

let my_string = my_str.to_string(); // returns String
Run Code Online (Sandbox Code Playgroud)

此外,您可以查看Match文档.