rustHow to use regex lookbehind in Rust?
Regex lookbehinds are a powerful tool for matching patterns in strings. In Rust, lookbehinds are supported through the regex
crate.
Example code
use regex::Regex;
let re = Regex::new(r"(?<=\d)\s+").unwrap();
let text = "1 2 3 4 5";
for cap in re.captures_iter(text) {
println!("{}", &cap[0]);
}
Output example
2
3
4
The code above uses a lookbehind to match any whitespace character (\s
) preceded by a digit (\d
). The lookbehind is specified with (?<=\d)
. The Regex::new
function is used to create a new Regex
object from the pattern. The captures_iter
method is then used to iterate over all matches in the text.
Code explanation
Regex::new
: creates a newRegex
object from the patterncaptures_iter
: iterates over all matches in the text(?<=\d)
: lookbehind to match any whitespace character (\s
) preceded by a digit (\d
)
Helpful links
Related
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- 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 replace all using regex in Rust?
- Regex example to match multiline string in Rust?
- How to replace all matches using Rust regex?
- How to parse a file with Rust regex?
- How to split a string with Rust regex?
More of Rust
- How to match whitespace with a regex in Rust?
- How to match the end of a line in a Rust regex?
- How to use regex to match a double quote in Rust?
- How to lock a Rust HashMap?
- How to match a URL with a regex in Rust?
- How to get the last element of a slice in Rust?
- How to get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to replace strings using Rust regex?
- How to use non-capturing groups in Rust regex?
See more codes...