fancy-regex crate multiple matches

点点圈 提交于 2021-02-05 09:26:17

问题


I'm using the fancy-regex crate since I need lookaheads in my Regex but it seems like it's not getting all of the matches in a string like I can with the regex crate which fancy-regex is built upon:

What I'm trying:

use fancy_regex::Regex;

let value = "Rect2(Vector2(0, 0), Vector2(0, 0))";

let re = Regex::new(r"\(([^()]*)\)").expect("Unable to create regex for values in parenthesis");
let results = re.captures(value).expect("Error running regex").expect("No matches found");

// Since 0 gets the all matches I print them individually.
// Prints 0, 0
println!("{:?}", results.get(1).unwrap());
// Error, no groups
println!("{:?}", results.get(2).unwrap());

Now if I try using the regex crate, which works for this regex because this particular one doesn't use lookahead like my other one, it gets all of the catpures.

use regex::Regex;

let value = "Rect2(Vector2(0, 0), Vector2(300, 500))";

let re = Regex::new(r"\(([^()]*)\)").expect("Unable to create regex for values in parenthesis");
let results = re.find_iter(value);

for i in results {
   // Prints 0, 0 first and then 300, 500 next time around.
   println!("{:?}", i);
}

I can't seem to find anything in fancy-regex that has the same functionality even though its built on the regex crate. All I can find is captures.iter() but I get only the first match with that too.

I made a demo of the regex crate here but since fancy_regex is not one of the 100 top crates I couldn't do the same for it.


回答1:


Note that your fancy_regex code looks for two captures in a single match, which is doomed to fail since your expression only contains one capture group. What you want (and what you're doing with regex) is a way to iterate through the matches, but it looks like fancy_regex does not have an easy way to do it. So you will need to do it manually:

let mut start = 0;
while let Some (m) = re.captures_from_pos (values, start).unwrap() {
   println!("{:?}", m.get (1).unwrap());
   start = m.get (0).unwrap().start() + 1; // Or you can use `end` to avoid overlapping matches
}


来源:https://stackoverflow.com/questions/62163974/fancy-regex-crate-multiple-matches

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!