花式正则表达式箱多个匹配

编程入门 行业动态 更新时间:2024-10-16 18:34:53
本文介绍了花式正则表达式箱多个匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用花式正则表达式板条箱,因为我需要在正则表达式中进行前瞻,但似乎它并没有像我使用构建花式正则表达式的正则表达式板条箱那样将所有匹配项放入字符串中:

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:

我正在尝试什么:

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

现在,如果我尝试使用 regex crate,它适用于这个正则表达式,因为这个特定的箱子不像我的另一个那样使用前瞻,它会得到所有的猫屎.

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

我似乎在花式正则表达式中找不到任何具有相同功能的东西,即使它是建立在正则表达式板条箱上的.我只能找到 captures.iter() 但我也只得到第一个匹配.

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.

我制作了 regex crate 的演示 这里 但由于 fancy_regex 不是 100 个顶级板条箱之一,我无法为它做同样的事情.

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.

推荐答案

请注意,您的 fancy_regex 代码在单个匹配项中查找两个捕获,这注定会失败,因为您的表达式只包含一个捕获团体.你想要的(以及你用 regex 做什么)是一种遍历匹配的方法,但看起来 fancy_regex 没有一个简单的方法来做到这一点.因此,您需要手动执行此操作:

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 }

更多推荐

花式正则表达式箱多个匹配

本文发布于:2023-11-22 14:40:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617845.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!