How to remove text between parentheses in a string using Rust

1 Answer

0 votes
use regex::Regex;

fn clean_string(text: &str) -> String {
    // Step 1: Remove parentheses and their content (non-greedy)
    let re_paren = Regex::new(r"\([^)]*\)").unwrap();
    let cleaned = re_paren.replace_all(text, "");

    // Step 2: Collapse multiple spaces into one
    let re_spaces = Regex::new(r"\s+").unwrap();
    let cleaned = re_spaces.replace_all(&cleaned, " ");

    // Step 3: Trim leading/trailing spaces
    cleaned.trim().to_string()
}

fn main() {
    let original = "Hello (remove this) from the future (and this too)";
    let result = clean_string(original);

    println!("Original: {}", original);
    println!("Cleaned : {}", result);
}



/*
run:

Original: Hello (remove this) from the future (and this too)
Cleaned : Hello from the future

*/

 



answered Dec 18, 2025 by avibootz

Related questions

...