Regex match exact text

In the first example we do something really simple, something for what we actually don't event need a regex, but it can show you the basic syntax in Rust.

We have a string The black cat climbed the green tree that we read from somewhere so we assume it is a String.

We would like to see if the series of characters cat is in the string.

So we create a Regex using the cat string as a regex and call the captures method. This returns an Option that is either Some match or None.

Cargo.toml

[package]
name = "regex-simple-match"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
regex = "1.9.6"

main.rs

use regex::Regex;

fn main() {
    let text = String::from("The black cat climbed the green tree");
    println!("{text}");

    let re = Regex::new(r"cat").unwrap();
    match re.captures(&text) {
        Some(value) => println!("Full match: {:?}", &value[0]),
        None => println!("No match"),
    };

    let re = Regex::new(r"dog").unwrap();
    match re.captures(&text) {
        Some(value) => println!("Full match: {:?}", &value[0]),
        None => println!("No match"),
    };
}

Output

The black cat climbed the green tree
Full match: "cat"
No match