Tokens and lexemes: tokenizer versus lexer

Token vs lexeme explained for compilers and linguistics, how a tokenizer differs from a lexer, and how styled, reversed or mirrored text affects the output.

“Token” and “lexeme” sound interchangeable, but they name different things, and their meanings shift depending on whether you are reading a compiler textbook or a linguistics paper. This guide explains what each term refers to, what a tokenizer or lexer actually does to text, and how to judge whether its output fits your purpose.

What tokenization and lexing actually change

Neither process edits the text itself. Both read a string and produce a separate, derived structure: a sequence of units, usually with labels and positions. The source characters stay as they were unless a separate normalization step, such as lowercasing, Unicode normalization or punctuation stripping, rewrites them first. Questions about data loss and reversibility are therefore questions about what the derived structure keeps, not about damage to the original.

Token and lexeme in programming languages

In compiler terminology, a lexeme is the exact run of characters in the source that matches a rule, and a token is the category assigned to that run, often paired with an attribute such as a value or a symbol-table reference. The rule itself is called a pattern. In the statement below, the characters “price” form a lexeme, and the token is an identifier carrying that name.

Input:  total = price * 2

Lexeme   Token
total    IDENTIFIER("total")
=        ASSIGN
price    IDENTIFIER("price")
*        STAR
2        NUMBER(2)

This output is illustrative, not captured from a specific tool; every language and lexer names its token types differently. Many lexers also discard whitespace and comments at this stage because the parser that consumes the tokens does not need them.

Token and lexeme in linguistics and NLP

In linguistics the relationship runs almost the other way. A token is one occurrence of a word form in running text, while a type is the distinct form regardless of how often it appears. A lexeme is the abstract dictionary unit behind a family of inflected forms: “run”, “runs”, “ran” and “running” are four forms of one lexeme, conventionally cited by its lemma, “run”. A tokenizer finds the tokens; identifying the lexeme is a later step, usually called lemmatization.

For example, a word tokenizer might split “She runs and they ran.” into six tokens: She, runs, and, they, ran and the final period. Two of those tokens, runs and ran, belong to the same lexeme. Whether the period counts as a token depends on the tokenizer's rules, so this split is illustrative.

Subword tokenizers used by large language models, built with methods such as byte-pair encoding or WordPiece, add a third meaning. Their tokens are frequent character or byte sequences that may be whole words, word fragments or punctuation. Those units are not lexemes in either sense, so a model's token count should not be read as a word count.

The terminology trap

A compiler lexeme is concrete text, while a linguistic lexeme is an abstraction. A compiler token is a category, while a linguistic token is a concrete occurrence. Before comparing figures or tools, check which tradition a document follows.

Aspect | Compilers and programming languages | Linguistics and NLP
Token | A category such as IDENTIFIER or NUMBER, often with an attribute | One occurrence of a word form in a text
Lexeme | The exact characters in the source that matched a pattern | An abstract word unit covering its inflected forms
Related term | Pattern: the rule that defines which lexemes belong to a token | Lemma: the citation form that names a lexeme
Produced by | The lexer, before parsing | Tokenizer for tokens; lemmatizer or dictionary lookup for lexemes

Tokenizer versus lexer: which one you need

In everyday programming the two names are often used interchangeably, and many tools called tokenizers perform full lexical analysis. When people do draw a line, it usually falls here: a tokenizer splits input into pieces, while a lexer also classifies each piece and attaches the information the next stage needs. Treat a tool's name as a hint rather than a specification, and check its documentation for what the output actually contains.

Criterion | Tokenizer (narrow sense) | Lexer
Output | A sequence of substrings or IDs | Typed tokens, often with values and positions
Classification | Optional or absent | Core function
Whitespace and comments | Depends on the tool | Often discarded unless the lexer is designed to keep them
Reversibility | Possible if separators and positions are kept | Usually lossy when whitespace and comments are dropped
Typical use | Word counts, search indexing, language-model input | Feeding a parser for code, configuration or query languages
  • Building or extending a parser for a programming, configuration or query language: use a lexer, because the parser needs token categories, not just strings.
  • Counting words, building a search index or preparing text for analysis: use a word tokenizer, then add lemmatization if forms such as “ran” and “runs” should be grouped.
  • Estimating limits or costs for a language model: use the tokenizer that belongs to that specific model, because different tokenizers can split the same text into different numbers of tokens.
  • Formatting, refactoring or round-tripping source code: choose a tool that keeps whitespace and comments or records exact character positions, so the original text can be rebuilt.

Python's standard-library tokenize module is one documented example of the position-preserving approach: it reports comments and line breaks as tokens and gives each token's type, string, and start and end positions, which is the information needed to annotate or reconstruct the source.

Will the output hold up on styled, reversed or mirrored text?

Tokenizers and lexers read the stored characters in their logical order, not what appears on screen. That produces predictable problems when the input has already gone through another text transformation.

  • Unicode “font” styling: generators that produce bold, italic or script-looking letters usually substitute characters from other Unicode blocks, such as Mathematical Alphanumeric Symbols. To a tokenizer these are different characters from ordinary Latin letters, so a styled word may not match its plain spelling, may split unexpectedly, or may fall outside the characters a lexer accepts in identifiers. NFKC normalization maps many of these characters back to plain letters, but it also folds other distinctions, so apply it deliberately.
  • Character-order reversal: reversing a string creates a new character sequence, so the resulting tokens are reversed strings rather than the original vocabulary. Reversing naively by code point can also detach combining accents or break emoji sequences before tokenization begins.
  • Visual mirroring with CSS: a transform such as scaleX(-1) changes only how the page is drawn. Copying the text or passing it to a tokenizer yields the original, unmirrored characters.
  • Bidirectional display: right-to-left scripts and invisible direction-control characters can make the displayed order differ from the stored order. A lexer follows the stored order, which is how the 2021 “Trojan Source” research showed that code which looks harmless to a reviewer can be read differently by a compiler. Editors, linters and compilers that flag unexpected direction controls in source code are the practical defense.

Copy and paste, accessibility and compatibility

Tokens are usually an internal representation, so the practical question is whether the input survives transfer intact. Copying from rich-text editors or web pages can bring in non-breaking spaces, curly quotes, zero-width characters or styled letters that look normal but change how text is split. Before tokenizing pasted text, inspect it for unexpected code points or route it through a plain-text step.

If people will also read the text, styled Unicode letters carry an accessibility cost: screen readers may announce them as symbol names, spell them out or skip them, depending on the software and its settings. No screen-reader testing was done for this guide, so check with the assistive technology your readers use. For text that must stay readable and searchable, keep the characters plain and apply visual styling with markup or CSS.

Online tokenizer playgrounds and text analyzers send your input to a third party. Avoid pasting credentials, private source code or personal data into them; an open-source tokenizer run locally gives the same kind of output without the exposure.

Checking a tool before you rely on it

The examples in this guide are illustrative, and no specific tool's output was tested. Token labels, punctuation handling, subword splits and normalization defaults vary by implementation and version, so run a small sample through the exact tool you plan to use.

  • Does the output keep whitespace, comments or character positions, or are they discarded?
  • Is any normalization, such as lowercasing or NFKC, applied by default?
  • How are punctuation, contractions and hyphenated words split?
  • What happens to styled Unicode letters, emoji and right-to-left text in your sample?
  • Does the tool run locally, or does it send text to a remote service?