home ~ projects ~ socials

Get Up To The Last Instance Of A String In Rust With nom

This is just a basic version of this, it might not work if you try to match more complicated things other than tags.

```cargo
[dependencies]
nom = "7.1.3"
```

#![allow(unused)]
use nom::bytes::complete::tag;
use nom::bytes::complete::take_until;
use nom::combinator::not;
use nom::multi::many0;
use nom::sequence::pair;
use nom::sequence::terminated;
use nom::IResult;
use nom::Parser;

fn get_to_last_instance_of<'a>(source: &'a str, target: &'a str) -> IResult<&'a str, String> {
  let (source, captured) = many0(
    pair(take_until(target), tag(target)).map(|hit| format!("{}{}", hit.0, hit.1))
  )(source)?;
  Ok((source, captured.join("")))
}

fn main() {
  let tests = vec![
    ("alfa bravo charlie", "bravo", " charlie", "alfa bravo"), 
    ("alfa bravo bravo bravo charlie", "bravo", " charlie", "alfa bravo bravo bravo"), 
  ];
  for test in tests.iter() {
    let result = get_to_last_instance_of(test.0, test.1).unwrap();
    assert_eq!(result.0, test.2, "Check remainder");
    assert_eq!(result.1, test.3, "Check captured");
  }
  println!("All Tests Passed");
}
Output:
All Tests Passed
-- end of line --