Regex generate iterator from things matched by the regex

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

Expected output:

[
    "foo",
    "bar",
    "baz qux",
]

Output:

[
    "",
    " ",
    " ",
    "",
]

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

Output:

[
    "foo",
    "bar",
    "baz\\ qux",
]

Oh, the bax qux thing was a mistake, I meant to put bar qux. find_iter does do what I want, thanks for your help!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.