Created
July 26, 2020 12:26
-
-
Save se1983/bf8cdacf2aafadfbd9ef39688bb9d2a9 to your computer and use it in GitHub Desktop.
Split string at regex and keep seperator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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