命名组匹配的正则表达式数组

标签 regex rust webassembly nsregularexpression

我想获取按时间顺序排列的所有捕获的组匹配的数组(它们在输入字符串中出现的顺序)。

因此,对于具有以下正则表达式的示例:

(?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/

相关文章:

php - 将标签包裹在某些单词周围

rust - 如何使用 Rust 与 Actix web 和 WebSockets 发送服务器事件?

rust - 流上的tokio::timeout总是发生

amazon-web-services - 使用Rusoto上传S3

c++ - 在 WASM 中访问当前 URL (c/c++)

javascript - 接收二维数组 args 作为 js.Value 并想要一个数组 ([]js.Value)

python - 通过正则表达式用自身的子集替换 Pandas 列

r - 在每个大写字母前添加下划线,后跟小写字母

python - 最好的方法是计算 python 中列表和字符串之间的匹配次数

Rust wasm32-unknown-unknown 数学函数不链接