Skip to content

Instantly share code, notes, and snippets.

@se1983
Created July 26, 2020 12:26
Show Gist options
  • Select an option

  • Save se1983/bf8cdacf2aafadfbd9ef39688bb9d2a9 to your computer and use it in GitHub Desktop.

Select an option

Save se1983/bf8cdacf2aafadfbd9ef39688bb9d2a9 to your computer and use it in GitHub Desktop.
Split string at regex and keep seperator
use regex::Regex; // 1.1.8
fn split_keep<'a>(r: &Regex, text: &'a str) -> Vec<&'a str> {
let mut result = Vec::new();
let mut last = 0;
for (index, matched) in text.match_indices(r) {
if last != index {
result.push(&text[last..index]);
}
result.push(matched);
last = index + matched.len();
}
if last < text.len() {
result.push(&text[last..]);
}
result
}
fn main() {
let seperator = Regex::new(r"(\[[^]]+])").expect("Invalid regex");
let splits = split_keep(&seperator, "[abc] content\n[xyz] next line");
for split in splits.chunks(2).map(|x| format!("{}{}", x[0], x[1])){
println!("XX: {:?}\n\n", split);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment