Skip to content

Instantly share code, notes, and snippets.

@PsychedelicShayna
Last active January 5, 2024 23:46
Show Gist options
  • Save PsychedelicShayna/5448a18033a28acc6d5fce2dbb9179f8 to your computer and use it in GitHub Desktop.
Save PsychedelicShayna/5448a18033a28acc6d5fce2dbb9179f8 to your computer and use it in GitHub Desktop.
Basically, for when Regex is overkill and you just want to extract substrings between deterministic start and end patterns. This Rust function will find every occurrence of a matching start/end pattern and return the contents in between.
pub fn extract(input: &str, pattern_start: &str, pattern_end: &str) -> Vec<String> {
let mut matches = Vec::new();
let mut position = 0;
while let Some(match_index) = input[position..].find(pattern_start) {
let start_index = position + match_index;
position = start_index + pattern_start.len();
if let Some(match_index) = input[position..].find(pattern_end) {
let end_index = position + match_index;
matches.push(input[position..end_index].to_string());
position = end_index + pattern_end.len();
} else {
break;
}
}
matches
}
fn main() {
let some_html = dont_ask_where_it_came_from();
let links = extract(some_html, "<a href=\"", "\"");
for link in links {
println!("You've now got links from HTML! {}", link);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment