Parser Capstone
Key/Value Parser
Split Once and Validate
A small parser can convert raw text into structured parts while rejecting incomplete input.
Program
Play the program to choose an input string and parse it into a key/value pair.
key_value_pair_parser.rs
fn main() {
let input = ;
match parse_pair(input) {
Some((key, value)) => println!("{key}:{value}"),
None => println!("invalid"),
}
}
fn parse_pair(input: &str) -> Option<(&str, &str)> {
let (key, value) = input.split_once('=')?;
if key.is_empty() || value.is_empty() {
None
} else {
Some((key, value))
}
}
fn main() {
let input = ;
match parse_pair(input) {
Some((key, value)) => println!("{key}:{value}"),
None => println!("invalid"),
}
}
fn parse_pair(input: &str) -> Option<(&str, &str)> {
let (key, value) = input.split_once('=')?;
if key.is_empty() || value.is_empty() {
None
} else {
Some((key, value))
}
}
fn main() {
let input = ;
match parse_pair(input) {
Some((key, value)) => println!("{key}:{value}"),
None => println!("invalid"),
}
}
fn parse_pair(input: &str) -> Option<(&str, &str)> {
let (key, value) = input.split_once('=')?;
if key.is_empty() || value.is_empty() {
None
} else {
Some((key, value))
}
}
split_once
`split_once('=')` separates the first key/value delimiter if it exists.
Option
`?` returns `None` immediately when the delimiter is missing.
validation
The parser rejects empty keys or values before returning structured data.