pub fn replace_host<'a>(bytes: &'a str, host_to_replace: &'a str, target_host: &'a str, target_port: u16) -> Cow<'a, str> { let matcher = format!("https?://{}", host_to_replace); Regex::new(&matcher) .unwrap() .replace_all(bytes, |item: &Captures| modify_url(item, target_host, target_port).unwrap_or(String::from(""))) } fn modify_url(caps: &Captures, host: &str, port: u16) -> Option { let first_match = caps.iter().nth(0)?; let match_item = first_match?; if let Ok(mut url) = Url::parse(match_item.as_str()) { url.set_host(Some(host)).ok(); url.set_port(Some(port)).ok(); Some(url.to_string()) } else { None } }