how to replace capture group while preserving surrounding context? #786
-
Describe your feature requestI am unable to replace an For example, I have the following regex: I need to replace only the ex.replace_all(&content, |caps: &Captures| {
let classes = caps.get(1).unwrap().as_str().to_owned() + " new-class";
// What do I return here to keep the `class="` and `"` while replacing the content between?
}) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
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: ®ex::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, the high level idea is to put the things that vary into capturing groups. But you could also take the approach of just splitting the entire regex into two pieces: the "before" piece and the "after" piece. It ends up being a little simpler in this case: fn replace(text: &str) -> String {
lazy_static! {
static ref RE: Regex = Regex::new(r#"(?x)
(?P<before>class(?:Name)?=["'].*)(?P<after>["'])
"#).unwrap();
}
RE.replace_all(text, |caps: ®ex::Captures| {
format!(
"{before} new-class{after}",
before=&caps["before"],
after=&caps["after"],
)
}).into_owned()
} Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1d2bb333370f5072e96fd9ae1ecf5b54 Note that one trick I used here was to use the infallible capturing index APIs. That is, |
Beta Was this translation helpful? Give feedback.
Here's one way:
Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9c070cb16dda0bb30a1871980fb8cf0c
Basically,…