Skip to content

how to replace capture group while preserving surrounding context? #786

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

You must be logged in to vote

Here's one way:

fn replace(text: &str) -> String {
    lazy_static! {
        static ref RE: Regex = Regex::new(r#"(?x)
            class(?P<suffix>(?:Name)?)
            =
            (?P<open>["'])(?P<existing>.*)(?P<close>["'])
        "#).unwrap();
    }
    RE.replace_all(text, |caps: &regex::Captures| {
        format!(
            "class{suffix}={open}{existing} new-class{close}",
            suffix=&caps["suffix"],
            open=&caps["open"],
            existing=&caps["existing"],
            close=&caps["close"],
        )
    }).into_owned()
}

Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9c070cb16dda0bb30a1871980fb8cf0c

Basically,…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@tqwewe
Comment options

@BurntSushi
Comment options

Answer selected by BurntSushi
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
Converted from issue

This discussion was converted from issue #785 on June 07, 2021 10:56.