rustHow do you match strings with regex in Rust?
Matching strings with regex in Rust is done using the regex
crate. This crate provides a Regex
type which can be used to match strings against a regular expression.
Example code
use regex::Regex;
let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
assert!(re.is_match("2018-01-01"));
Output example
(no output)
Code explanation
use regex::Regex
: imports theRegex
type from theregex
crate.Regex::new(r"^\d{4}-\d{2}-\d{2}$")
: creates a newRegex
object from the given regular expression..unwrap()
: unwraps theResult
returned byRegex::new
and panics if the regular expression is invalid.re.is_match("2018-01-01")
: checks if the given string matches the regular expression.
Helpful links
More of Rust
- How to use non-capturing groups in Rust regex?
- How to use regex to match a double quote in Rust?
- How to use regex to match a group in Rust?
- How to parse JSON string in Rust?
- How to perform matrix operations in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to use a tuple as a key in a Rust HashMap?
- How to use Unicode in a regex in Rust?
- How to replace all matches using Rust regex?
- How to get a capture group using Rust regex?
See more codes...