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 replace a capture group using Rust regex?
- How to get a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to split a string with Rust regex?
- How to use regex lookahead in Rust?
- How to ignore case in Rust regex?
- How to get all matches from a Rust regex?
- How to escape dots with regex in Rust?
- Regex example to match multiline string in Rust?
More of Rust
- How to match the end of a line in a Rust regex?
- How to split a string with Rust regex?
- How to match a URL with a regex in Rust?
- How to use regex to match a group in Rust?
- How to ignore case in Rust regex?
- How to create a Rust regex from a string?
- How to use backslash in regex in Rust?
- Hashshet example in Rust
- How to use a tuple as a key in a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
See more codes...