Regular Expressions in Rust: A Complete Guide for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to Regular Expressions in Rust



Regular expressions (regex) are a powerful tool for searching, extracting, and replacing text based on a given pattern. In Rust, the regex crate is used for working with regular expressions — one of the most popular and performant libraries in the ecosystem. In this article, we will cover the basics of working with regex in Rust, starting from installation to practical examples.



Why should you learn regular expressions in Rust? The language offers safe and fast text processing, and the regex crate guarantees no memory leaks and high execution speed. This makes Rust an excellent choice for parsing logs, form validation, processing configuration files, and other tasks.



Installing and Adding the regex Crate



To get started, add the regex dependency to your Cargo.toml file:



[dependencies]regex = "1.10"


After that, import the module in your code:



use regex::Regex;


The main structure you will work with is Regex. You can create an instance using the Regex::new() method, which returns a Result because the pattern might be invalid.



fn main() {    let re = Regex::new(r"^\\d{3}-\\d{2}-\\d{4}$").unwrap();    println!("Regex created: {}", re.as_str());}


Note: the pattern is written in raw strings (r"...") to avoid escaping backslashes.



Basic Operations with Regular Expressions



1. Checking for a Match: is_match



The is_match method returns true if the pattern is found in the string:



use regex::Regex;

fn main() { let re = Regex::new(r"hello").unwrap(); let text = "hello world"; if re.is_match(text) { println!("Match found!"); } else { println!("No match"); }}


Output: Match found!



2. Finding the First Match: find



The find method returns Option<Match> — the first match with position information:



use regex::Regex;

fn main() { let re = Regex::new(r"\\d+").unwrap(); let text = "Code: 12345, price: 678"; if let Some(m) = re.find(text) { println!("Found: '{}' (position {}..{})", m.as_str(), m.start(), m.end()); }}


Output: Found: '12345' (position 5..10)



3. Finding All Matches: find_iter



To get all matches, use the find_iter iterator:



use regex::Regex;

fn main() { let re = Regex::new(r"\\d+").unwrap(); let text = "Numbers: 42, 100, 7"; for m in re.find_iter(text) { println!("Number: {}", m.as_str()); }}


Output:

Number: 42Number: 100Number: 7


4. Extracting Groups: captures



Groups in the pattern (denoted by parentheses) allow you to extract parts of a match:



use regex::Regex;

fn main() { let re = Regex::new(r"(\\w+)@(\\w+)\\.(\\w+)").unwrap(); let email = "user@example.com"; if let Some(caps) = re.captures(email) { println!("Full email: {}", &caps[0]); println!("Name: {}", &caps[1]); println!("Domain: {}", &caps[2]); println!("Zone: {}", &caps[3]); }}


Output:

Full email: user@example.comName: userDomain: exampleZone: com


Practical Usage Examples



Example 1: Phone Number Validation



Let's check if a string matches the format of a Russian phone number (e.g., +7-XXX-XXX-XX-XX):



use regex::Regex;

fn v

Blogs

Book Recommendations