How can I find a subsequence in a &[u8] slice?

后端 未结 4 1199
耶瑟儿~
耶瑟儿~ 2020-12-03 20:45

I have a &[u8] slice over a binary buffer. I need to parse it, but a lot of the methods that I would like to use (such as str::find) don\'t see

4条回答
  •  萌比男神i
    2020-12-03 21:33

    How about Regex on bytes? That looks very powerful. See this Rust playground demo.

    extern crate regex;
    
    use regex::bytes::Regex;
    
    fn main() {
        //see https://doc.rust-lang.org/regex/regex/bytes/
    
        let re = Regex::new(r"say [^,]*").unwrap();
    
        let text = b"say foo, say bar, say baz";
    
        // Extract all of the strings without the null terminator from each match.
        // The unwrap is OK here since a match requires the `cstr` capture to match.
        let cstrs: Vec =
            re.captures_iter(text)
              .map(|c| c.get(0).unwrap().start())
              .collect();
    
        assert_eq!(cstrs, vec![0, 9, 18]);
    }
    

提交回复
热议问题