Introduction: Regular Expressions in Rust — a Powerful Tool for Text Processing
Regular expressions (regex) are an essential part of any developer's toolkit when working with text. In Rust, which is renowned for its performance and safety, working with regular expressions is implemented through the popular regex crate. This library provides a fast and reliable way to search, extract, and replace text patterns.
In this article, we will thoroughly examine how to use regular expressions in Rust: from installing the crate to advanced techniques. You will learn how to check for matches, extract data, replace text, and handle errors. All code examples are written in Rust and ready to use.
1. Installing and Importing the regex Crate
To work with regular expressions in Rust, you need to add the regex crate to the Cargo.toml file:
[dependencies]regex = "1"After that, you can import the necessary modules into your code:
use regex::Regex;The regex crate automatically compiles regular expressions into an efficient internal format, ensuring high performance.
2. Basic Operations with regex in Rust
2.1 Checking for a Match (is_match)
The is_match method returns true if the string contains at least one match for the pattern:
use regex::Regex;
fn main() { let re = Regex::new(r"\\d+").unwrap(); let text = "Today is December 25";
if re.is_match(text) { println!("The string contains numbers"); } else { println!("No numbers found"); }}This method is useful for quick validation: checking if a string contains an email, phone number, or other patterns.
2.2 Finding the First Match (find)
The find method returns the first match as a Match structure, which contains the start and end of the match:
use regex::Regex;
fn main() { let re = Regex::new(r"\\b\\w+@\\w+\\.\\w+\\b").unwrap(); let text = "My email: user@example.com, and also admin@test.org";
if let Some(mat) = re.find(text) { println!("Found email: {}", mat.as_str()); println!("Position: {}..{}", mat.start(), mat.end()); }}Execution result:
Found email: user@example.comPosition: 11..272.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 = "Prices: 100, 250 and 500 rubles";
for mat in re.find_iter(text) { println!("Number: {}", mat.as_str()); }}Output:
Number: 100Number: 250Number: 5003. Extracting Groups Using Capturing Parentheses
One of the most powerful features of regex is capturing groups. They allow you to extract parts of a match:
use regex::Regex;
fn main() { let re = Regex::new(r"(\\w+)@(\\w+)\\.(\\w+)").unwrap(); let text = "user@example.com";
if let Some(caps) = re.captures(text) { println!("Full email: {}", &caps[0]); println!("Username: {}", &caps[1]); println!("Domain: {}", &caps[2]); println!("Zone: {}", &caps[3]); }}Groups are numbered starting from 1. Group 0 is the entire match.
You can also use named groups for more readable code:
use regex::Regex;
fn main() { let re = Regex::new(r"(?P<name>\\w+)@(?P<domain>\\w+\\.\\w+)").unwrap(); let text = "admin@test.org";
if let Some(caps) = re.captures(text) { println!("Name: {}", caps.name("name").unwrap().as_str