How to remove parentheses and the text inside them from a string in Rust

1 Answer

0 votes
use regex::Regex;

/**
 * Remove all parentheses and the text inside them.
 *
 * @param text  The input string
 * @return      The cleaned string
 */
fn remove_parentheses_with_content(text: &str) -> String {
    // Remove parentheses and everything inside them
    let re = Regex::new(r"\([^)]*\)").unwrap();
    let cleaned = re.replace_all(text, " ");

    // Collapse multiple spaces into one
    let collapsed = cleaned
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");

    // Final trim of leading/trailing spaces
    collapsed.trim().to_string()
}

fn main() {
    let text = "(An) API (API) (is a) (connection) connects (between) computer programs";
    let output = remove_parentheses_with_content(text);

    println!("{}", output);
}



/*
run:

API connects computer programs

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz

Related questions

...