Regular Expressions in Rust
Our first program demonstrates the use of regular expressions in Rust. Here’s the full source code with explanations:
use regex::Regex;
fn main() {
// This tests whether a pattern matches a string.
let re = Regex::new(r"p([a-z]+)ch").unwrap();
println!("{}", re.is_match("peach"));
// Find the first match for the regexp.
println!("{:?}", re.find("peach punch"));
// This finds the start and end indexes for the match.
if let Some(mat) = re.find("peach punch") {
println!("idx: {:?}", (mat.start(), mat.end()));
}
// The captures method returns information about both
// the whole-pattern matches and the submatches.
if let Some(caps) = re.captures("peach punch") {
println!("{:?}", caps.iter().collect::<Vec<_>>());
}
// Find all matches for a regexp.
println!("{:?}", re.find_iter("peach punch pinch").collect::<Vec<_>>());
// Providing a non-negative integer as the second
// argument to these functions will limit the number
// of matches.
println!("{:?}", re.find_iter("peach punch pinch").take(2).collect::<Vec<_>>());
// The regex package can also be used to replace
// subsets of strings with other values.
println!("{}", re.replace_all("a peach", "<fruit>"));
// The replace method allows you to transform matched
// text with a given function.
let result = re.replace_all("a peach", |caps: ®ex::Captures| {
format!("{}", caps[0].to_uppercase())
});
println!("{}", result);
}
To run the program, put the code in regular_expressions.rs
and use cargo run
.
$ cargo run
true
Some(Match { start: 0, end: 5 })
idx: (0, 5)
[Some(Match { start: 0, end: 5 }), Some(Match { start: 1, end: 3 })]
[Match { start: 0, end: 5 }, Match { start: 6, end: 11 }, Match { start: 12, end: 17 }]
[Match { start: 0, end: 5 }, Match { start: 6, end: 11 }]
a <fruit>
a PEACH
For a complete reference on Rust regular expressions, check the regex
crate documentation.
Note that in Rust, we use the regex
crate for regular expressions, which needs to be added to your Cargo.toml
file:
[dependencies]
regex = "1.5"
The Rust version provides similar functionality to the Go version, but with some differences due to Rust’s ownership and borrowing system, and the design of the regex
crate. For example, Rust uses Option
and Result
types for handling potential failures, and iterators for multiple matches.