我正在尝试匹配特定字符后的两个字符。尾随值可能包含指定字符,这没问题,但我还需要捕获该指定字符作为下一个捕获组的开头。
这段代码应该能说明我的意思:
extern crate regex;
use regex::Regex;
pub fn main() {
let re = Regex::new("(a..)").unwrap();
let st = String::from("aba34jf baacdaab");
println!("String to match: {}", st);
for cap in re.captures_iter(&st) {
println!("{}", cap[1].to_string());
// Prints "aba" and "aac",
// Should print "aba", "a34", "aac", "acd", "aab"
}
}
如何在不使用环顾四周的情况下获得重叠捕获(Rust 中的正则表达式箱不支持)?是否有类似于 Python ( as mentioned here ) 但在 Rust 中的东西?
编辑:
按照 BurntSushi5 的建议使用 onig,我们得到以下信息:
extern crate onig;
use onig::*;
pub fn main() {
let re = Regex::new("(?=(a.{2}))").unwrap();
let st = String::from("aba34jf baacdaab");
println!("String to match: {}", st);
for ch in re.find_iter(&st) {
print!("{} ", &st[ch.0..=ch.1+2]);
// aba a34 aac acd aab, as it should.
// but we have to know how long the capture is.
}
println!("");
}
现在的问题是您必须知道正则表达式的长度,因为前瞻组不会捕获。有没有办法在事先不知道长度的情况下捕获前瞻性正则表达式?如果我们将 (?=(a.+))
作为正则表达式,我们将如何打印出来?
最佳答案
关于regex - 如何在 Rust 中获取重叠的正则表达式捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57497045/