Regex to match key-value pairs

Rust

examples/regex-match-key-value-pairs/Cargo.toml

[package]
name = "regex-match-key-value-pairs"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
regex = "1.10.3"

examples/regex-match-key-value-pairs/src/main.rs

use regex::Regex;

fn main() {
    let re = Regex::new(r#"(\w+)="([^"]+)""#).unwrap();

    for text in vec![r#"name="foo""#, "anwser=42"] {
        println!("{text}");
        match re.captures(text) {
            None => {}
            Some(cap) => {
                println!("'{}'", &cap[1]);
                println!("'{}'", &cap[2]);
            }
        }
        println!("---");
    }

    println!("====");

    let re = Regex::new(r#"(\w+)=(?:"([^"]+)"|(\d+))"#).unwrap();

    for text in vec![r#"name="foo""#, "anwser=42"] {
        println!("{text}");
        match re.captures(text) {
            None => {}
            Some(cap) => {
                let key = &cap[1];
                let value = if cap.get(2).is_some() {
                    &cap[2]
                } else {
                    &cap[3]
                };

                println!("'{}'", key);
                println!("'{}'", value);
            }
        }
        println!("---");
    }

    println!("====");

    // title="hello \"foo\" bar"
    // title="hello \\"foo\" bar"
    // title="hello\\"
    let text = r#"  name="foo"  anwser=42  "#;
    println!("{text}");
    for cap in re.captures_iter(text) {
        let key = &cap[1];
        let value = if cap.get(2).is_some() {
            &cap[2]
        } else {
            &cap[3]
        };
        println!("'{}'", key);
        println!("'{}'", value);
        println!("----");
    }

    // for (_, [key, value]) in re.captures_iter(text).map(|cap| {
    //     let key = &cap[1];
    //     let value = if cap.get(2).is_some() {
    //         &cap[2]
    //     } else {
    //         &cap[3]
    //     };
    //     (key, value)
    // }) {
    //     println!("'{}'", key);
    //     println!("'{}'", value);
    // }
}

examples/regex-match-key-value-pairs/out.txt

name="foo"
'name'
'foo'
---
anwser=42
---
====
name="foo"
'name'
'"foo"'
---
anwser=42
'anwser'
'42'
---

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo