home ~ projects ~ socials

Get A String Up Until Another String With nom In Rust

This is my most recent way to do this as of Oct. 2024

```cargo
[dependencies]
nom = { version = "7.1.3" }
```

use nom::branch::alt;
use nom::bytes::complete::is_not;
use nom::bytes::complete::tag;
use nom::character::complete::multispace1;
use nom::combinator::not;
use nom::multi::many1;
use nom::sequence::pair;
use nom::IResult;
use nom::Parser;

fn main() {
    let results = get_until_string("alfa:bravo: charlie");
    println!("{}", results.unwrap().1);
}

pub fn get_until_string(source: &str) -> IResult<&str, String> {
    let (source, result) = many1(alt((
        is_not(":"),
        pair(tag(":"), not(multispace1)).map(|x| x.0),
    )))
    .parse(source)?;
    Ok((source, result.join("")))
}
Output:
alfa:bravo
-- end of line --