rustHow to use regex with bytes in Rust?
Regex can be used with bytes in Rust by using the regex
crate. This crate provides a Regex
type which can be used to match against byte slices.
use regex::Regex;
let re = Regex::new(r"\d+").unwrap();
let bytes = b"123 456";
for cap in re.captures_iter(bytes) {
println!("{}", &cap[0]);
}
Output example
123
456
Code explanation
use regex::Regex
: imports theRegex
type from theregex
crate.Regex::new(r"\d+")
: creates a newRegex
object from the given pattern.captures_iter(bytes)
: returns an iterator over all the non-overlapping captures in the given byte slice.&cap[0]
: returns the first capture group of the given capture.
Helpful links
Related
- How to replace all matches using Rust regex?
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to replace strings using Rust regex?
- How to escape dots with regex in Rust?
- How to split a string with Rust regex?
- Regex example to match multiline string in Rust?
- How to get a capture group using Rust regex?
- How to find the first match in a Rust regex?
More of Rust
- How to replace strings using Rust regex?
- How to parse JSON string in Rust?
- How to convert the keys of a Rust HashMap to a vector?
- How to escape dots with regex in Rust?
- How to add matrices in Rust?
- How do I copy a variable in Rust?
- How to parse a file with Rust regex?
- How to declare a constant HashSet in Rust?
- How to get all values from a Rust HashMap?
- How to convert a Rust HashMap to a BTreeMap?
See more codes...