rustHow to find the first match in a Rust regex?
The find method of the Regex type can be used to find the first match in a Rust regex.
Example code
let re = Regex::new(r"\d+").unwrap();
let text = "123 456 789";
let first_match = re.find(text).unwrap();
println!("{:?}", first_match);
Output example
Some((0, 3))
Code explanation
-
let re = Regex::new(r"\d+").unwrap();: This line creates a newRegexobject from the given pattern. Theunwrapmethod is used to handle any errors that may occur. -
let text = "123 456 789";: This line creates aStringobject containing the text to be searched. -
let first_match = re.find(text).unwrap();: This line calls thefindmethod of theRegexobject to find the first match in the given text. Theunwrapmethod is used to handle any errors that may occur. -
println!("{:?}", first_match);: This line prints the result of thefindmethod.
Helpful links
Related
- How to replace strings using Rust regex?
- Regex example to match multiline string in Rust?
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to split a string with Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use negation in Rust regex?
- How to use regex lookbehind in Rust?
- How to use regex lookahead in Rust?
- How to ignore case in Rust regex?
More of Rust
- Regex example to match multiline string in Rust?
- How to extend a Rust HashMap?
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to use regex lookbehind in Rust?
- How to compare two Rust HashMaps?
- How to replace a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to replace strings using Rust regex?
- How to split a string with Rust regex?
See more codes...