Skip to content

Regex to match crate and version #1143

Answered by BurntSushi
kirawi asked this question in Q&A
Discussion options

You must be logged in to vote

This program, strictly speaking, satisfies your prompt:

use regex::Regex;

fn main() -> anyhow::Result<()> {
    let hay = "
hello
hello = '1.2.3'
hello = { version = '1.2.3' }
hello = { version = '1.2.3', features = [''] }
";
    let re = Regex::new(
        r"(?xm)
          (?<krate>^\S+)(?:\s*=\s*(?:\{\s*)?(?:version\s*=\s*)?'(?<version>[^']+)')?
        ",
    )
    .unwrap();

    for caps in re.captures_iter(hay) {
        dbg!(&caps);
    }
    Ok(())
}

And the Cargo.toml:

[package]
publish = false
name = "d1143"
version = "0.1.0"
edition = "2021"

[dependencies]
anyhow = "1.0.77"
regex = "1.10.2"

[[bin]]
name = "d1143"
path = "main.rs"

And then running it gives:

$ cargo run -q
[…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@kirawi
Comment options

Answer selected by kirawi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants