Parsing strings is always a challenge when learning a programming language. But most languages have similar methods and parsing concepts.
In Rust we invoke find and rfind to locate strings. With these functions we can get substrings between, before and after other strings.
Suppose we are reading lines from a log file, or other text file that has formatted data. Here we see the required output for a certain line of input.
Input = "DEFINE:A=TWO" Between("DEFINE:", "=TWO") = "A"
In Rust, we call find()
and rfind and place these calls in if
-statements. We use string
slices to return the desired substrings.
Between()
indicates that the return value is borrowed from the "value" string
. The result is a substring of value.before()
does not find an "after" part. It also uses string
slice syntax.After()
is the same thing, but in reverse, as the before function. It returns the string
slice after a certain substring.fn between<'value>(value: &'value str, a: &str, b: &str) -> &'value str { // Find the two strings. if let Some(pos_a) = value.find(a) { if let Some(pos_b) = value.rfind(b) { // Return the part in between the 2 strings. let adjusted_pos_a = &pos_a + a.len(); if adjusted_pos_a < pos_b { return &value[adjusted_pos_a..pos_b]; } } } return ""; } fn before<'value>(value: &'value str, a: &str) -> &'value str { // Find the string and return the part before. if let Some(pos_a) = value.find(a) { return &value[0..pos_a]; } return ""; } fn after<'value>(value: &'value str, a: &str) -> &'value str { // Find the string and return the part after. if let Some(pos_a) = value.rfind(a) { let adjusted_pos_a = pos_a + a.len(); if adjusted_pos_a < value.len() { return &value[adjusted_pos_a..]; } } return ""; } fn main() { let test = "DEFINE:A=TWO"; println!("{}", between(test, "DEFINE:", "=")); println!("{}", between(test, ":", "=")); println!("{}", before(test, ":")); println!("{}", before(test, "=")); println!("{}", after(test, ":")); println!("{}", after(test, "DEFINE:")); println!("{}", after(test, "=")); }A A DEFINE DEFINE:A A=TWO A=TWO TWO
With Rust, borrowing variables is the most unique part of developing between, before and after functions. We have to indicate what things own other things.