joydeep bhattacharjee
joydeep bhattacharjee

Reputation: 1319

Unable to use a regex to extract words: no method to_string for Match

I am trying to loop over a sentence and get the words using a regex:

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();
        }
    }
}

I am getting the below error.

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`

What am I missing?

Upvotes: 1

Views: 735

Answers (1)

Akiner Alkan
Akiner Alkan

Reputation: 6918

To get &str from the Match you can use this:

let my_str = cap.as_str(); // returns &str

If you really want to get a String, you can call to_string() on it:

let my_string = my_str.to_string(); // returns String

Also, you can take a look at the Match documentation.

Upvotes: 5

Related Questions