rustHow to use regex to match a group in Rust?
Regex (regular expressions) can be used to match a group in Rust. To do this, you need to use the regex
crate.
Example code
extern crate regex;
use regex::Regex;
fn main() {
let re = Regex::new(r"(\w{5})").unwrap();
let text = "The quick brown fox";
for cap in re.captures_iter(text) {
println!("{}", &cap[1]);
}
}
Output example
quick
brown
fox
Code explanation
extern crate regex;
: imports theregex
crate.use regex::Regex;
: imports theRegex
type from theregex
crate.let re = Regex::new(r"(\w{5})").unwrap();
: creates a newRegex
object with the pattern(\w{5})
.let text = "The quick brown fox";
: creates a string to match against.for cap in re.captures_iter(text) {
: iterates over the captures of theRegex
object.println!("{}", &cap[1]);
: prints the capture group.
Helpful links
Related
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to match whitespace with a regex in Rust?
- How to use Unicode in a regex in Rust?
- How to match a URL with a regex in Rust?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
- How to get a capture group using Rust regex?
- How to split a string with Rust regex?
- How to use non-capturing groups in Rust regex?
More of Rust
- How to use regex to match a double quote in Rust?
- How to replace all matches using Rust regex?
- How to split a string with Rust regex?
- How to get struct value in Rust
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to get a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use groups in a Rust regex?
See more codes...