Match Char Classes In A Tiny Tokenizer
A per-character match with literal, range, and wildcard arms turns a raw string into tokens: symbols emit immediately, word chars accumulate.
Code
#[derive(Debug, PartialEq)]
enum Token {
Number(u32),
Ident(String),
Plus,
Dash,
}
fn parse_word(word: &str) -> Token {
// All digits -> Number, otherwise -> Ident
if word.chars().all(|c| c.is_ascii_digit()) {
Token::Number(word.parse().expect("digits only"))
} else {
Token::Ident(String::from(word))
}
}
fn tokenize(input: &str) -> Vec<Token> {
let mut tokens = Vec::new();
let mut word = String::new();
for c in input.chars() {
// Range and or-patterns: alphanumerics count as word characters
let is_word = matches!(c, '0'..='9' | 'a'..='z' | 'A'..='Z');
if !is_word && !word.is_empty() {
tokens.push(parse_word(&word));
word.clear();
}
match c {
// Literal patterns: single-character symbols emit a token immediately
'+' => tokens.push(Token::Plus),
'-' => tokens.push(Token::Dash),
'0'..='9' | 'a'..='z' | 'A'..='Z' => word.push(c),
// Wildcard arm: everything else is just a separator
_ => {}
}
}
if !word.is_empty() {
tokens.push(parse_word(&word));
}
tokens
}
fn main() {
let tokens = tokenize("height-42+width");
println!("{:?}", tokens);
assert_eq!(
tokens,
vec![
Token::Ident(String::from("height")),
Token::Dash,
Token::Number(42),
Token::Plus,
Token::Ident(String::from("width")),
]
);
println!("token count: {}", tokens.len());
}How the snippet works
Match Char Classes In A Tiny Tokenizer is built around the functions parse_word, tokenize and main.
Repetition is confined to for c in input.chars() — the rest of the file is straight-line. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.
Using it
The primary signature is fn parse_word(word: &str) -> Token
The demo output is labeled (token count:); each label names the call that printed it.
The sequence tokenize lives in main; running the file triggers it.
Key statements
fn parse_word(word: &str) -> Token {
// All digits -> Number, otherwise -> Ident
if word.chars().all(|c| c.is_ascii_digit()) {
Token::Number(word.parse().expect("digits only"))
} else {
Token::Ident(String::from(word))
}
}
Interactive Tools for This Topic
LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- What does Match Char Classes In A Tiny Tokenizer print when run?
- Invoke the file as-is — the `token count:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.