Reputation: 1319
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
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