我正在尝试匹配特定字符后的两个字符。尾随值可能包含指定的字符,这是可以的,但我还需要捕获该指定的字符作为下一个捕获组的开头。
这段代码应该说明我的意思:
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 中的东西(如这里提到的)但在 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.+))如果我们有像正则表达式这样的东西,我们将如何打印它?
| 归档时间: | 
 | 
| 查看次数: | 3106 次 | 
| 最近记录: |