// include the latest version of the regex crate in your Cargo.toml
extern crate regex;
use regex::Regex;
fn main() {
let regex = Regex::new(r"(?xsm) # free-spacing mode, DOTALL, multi-line
(?=.*?blue) # if blue isn't there, fail without delay
########### LINE SKIPPER / COUNTER ############
(?: # start non-capture group
# the aim is to skip lines that don't contain blue
# and capture a corresponding digit sequence
(?: # skip one line that doesn't contain blue
^ # beginning of line
(?:(?!blue)[^\r\n])* # zero or more chars
# that do not start blue
(?:\r?\n) # newline chars
)
# With each line skipped, let Group 1 capture
# an ever-growing portion of the string of numbers
(?= # lookahead
.* # Go to the end of the file
( # start Group 1
~\d+ # match a tilde and digits
(?(1)\1) # if Group 1 is set, match Group 1
) # end Group 1
) # end lookahead
)*+ # end counter-line-skipper: zero or more times
# the possessive + forbids backtracking
.*? # lazily match any chars up to...
blue # match blue
.* # Get to the end of the data
~ # match a tilde
\K # drop what we matched so far
\d+ # match digits. This is the match!
(?=(?(1)\1)) # if Group 1 has been set, match it
").unwrap();
let string = "Paint it white
Paint it black
Why not blue?
Or red or brown?
~10~9~8~7~6~5~4~3~2~1";
let substitution = "";
// result will be a String with the substituted value
let result = regex.replace(string, substitution);
println!("{}", result);
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Rust, please visit: https://docs.rs/regex/latest/regex/