I'm trying to split a string based on a regex, however the split method in the regex crate splits on things that aren't matched by the regex. I want the iterator to include only the things that are matched by the regex, but none of the methods i found to "invert" a regex work, and there doesn't seem to be a method for this in the Regex struct. How would i do this?
use regex::Regex;
println!("{:#?}", Regex::new(r"(?:\\.|\S)+").unwrap().split("foo bar baz\\ qux").collect::<Vec<&str>>());
Not sure how did you get bax qux in the expected output, since that substring is not present in the original string. Anyway, does the Regex::find_iter do what you want? An example (playground):
fn main() {
use regex::Regex;
println!(
"{:#?}",
Regex::new(r"(?:\\.|\S)+")
.unwrap()
.find_iter("foo bar baz\\ qux")
.map(|m| m.as_str())
.collect::<Vec<&str>>()
);
}