How to extract a substring between two tags using RegEx in Rust

1 Answer

0 votes
use regex::Regex;

fn extract_content_between_tags(s: &str, tag_name: &str) -> Option<String> {
    // Build a regex pattern using the specified tag name
    let pattern = format!(r"<{}>(.*?)</{}>", tag_name, tag_name);

    // Compile the regex pattern
    let re = Regex::new(&pattern).unwrap();

    // Find the first match
    if let Some(captures) = re.captures(s) {
        // Return the content inside the tags
        if let Some(content) = captures.get(1) {
            return Some(content.as_str().to_string());
        }
    }

    // Return None if no match is found
    None
}

fn main() {
    let s = "abcd <tag>efg hijk lmnop</tag> qrst uvwxyz";

    // Call the function to extract the substring
    if let Some(content) = extract_content_between_tags(s, "tag") {
        println!("Extracted content: {}", content);
    } else {
        println!("No matching tags found.");
    }
}


      
/*
run:

Extracted content: efg hijk lmnop
     
*/

 



answered Apr 3 by avibootz
...