Skip to content

how to iterate over matches where the next match must start immediately following the previous match? #888

Answered by BurntSushi
xtofs asked this question in Q&A
Discussion options

You must be logged in to vote

No, there is no such anchor. The reason why is because such a thing is not really a property of the regex or its match semantics. A regex itself doesn't have any concept of iteration. Iteration is a protocol built on top of the regex pattern. So in order to do something like that, you can't use captures_iter. You'll have to roll your own iteration logic. For example, it's very easy to do if you can assume that your regex never produces any empty matches (if it can, then the logic below won't terminate):

use regex::Regex;

fn main() {
    let mut haystack = "abcdefghi jklmnopqr";
    let re = Regex::new(r"^\w{3}").unwrap();
    while let Some(caps) = re.captures(haystack) {
        dbg!(&caps

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@xtofs
Comment options

Answer selected by BurntSushi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants