我想获取按时间顺序排列的所有捕获的组匹配的数组(它们在输入字符串中出现的顺序)。
因此,对于具有以下正则表达式的示例:
(?P<fooGroup>foo)|(?P<barGroup>bar)
以及以下输入:
foo bar foo
我想要得到类似于以下输出的内容:
[("fooGroup", (0,3)), ("barGroup", (4,7)), ("fooGroup", (8,11))]
这是否可以在不手动对所有匹配项进行排序的情况下完成?
最佳答案
我不知道“无需手动对所有匹配项进行排序”是什么意思,但是此 Rust 代码会生成您想要的这种特定模式样式的输出:
use regex::Regex;
fn main() {
let pattern = r"(?P<fooGroup>foo)|(?P<barGroup>bar)";
let haystack = "foo bar foo";
let mut matches: Vec<(String, (usize, usize))> = vec![];
let re = Regex::new(pattern).unwrap();
// We skip the first capture group, which always corresponds
// to the entire pattern and is unnamed. Otherwise, we assume
// every capturing group has a name and corresponds to a single
// alternation in the regex.
let group_names: Vec<&str> =
re.capture_names().skip(1).map(|x| x.unwrap()).collect();
for caps in re.captures_iter(haystack) {
for name in &group_names {
if let Some(m) = caps.name(name) {
matches.push((name.to_string(), (m.start(), m.end())));
}
}
}
println!("{:?}", matches);
}
这里唯一真正的技巧是确保 group_names
是正确的。对于 (?P<name1>re1)|(?P<name2>re2)|...|(?P<nameN>reN)
形式的任何模式都是正确的其中每个 reI
不包含其他捕获组。
关于命名组匹配的正则表达式数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71620526/