Last active
March 26, 2023 04:21
-
-
Save matthewjberger/d6e8f6ca69310b3f1916b6a92dbf7553 to your computer and use it in GitHub Desktop.
Extract or remove substrings between curly brackets in rust https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c51dd846d0b0361855cbd6a19c026539
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let s = "system/{id}/start/{mode}"; | |
let substrings = extract_substrings(s); | |
assert_eq!(substrings, vec!["id", "mode"]); | |
let removed = remove_substrings(&s, &substrings); | |
assert_eq!(removed, "system/{}/start/{}"); | |
} | |
fn extract_substrings(s: &str) -> Vec<&str> { | |
s.split('{') | |
.skip(1) | |
.filter_map(|substr| substr.split_once('}')) | |
.map(|(outer, _)| outer) | |
.collect() | |
} | |
fn remove_substrings(s: &str, substrings: &[&str]) -> String { | |
let mut result = String::from(s); | |
for substring in substrings { | |
result = result.replace(&format!("{{{}}}", substring), "{}"); | |
} | |
result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment