This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Parsimmon Parser Combinator Cheatsheet

A quick reference guide for Parsimmon: parser combinator library for JavaScript, atomic parsers, sequencing, alternatives, separators, and mapping.

· Published

Parsimmon is a small, elegant parser combinator library for JavaScript and Node.js.

Basic Example

const P = require('parsimmon');

// Create a parser matching one or more lowercase letters
const word = P.regexp(/[a-z]+/);

const result = word.parse('hello');
// => { status: true, value: 'hello' }

Atomic Parsers

P.string('function');   // Exact string literal
P.regexp(/[0-9]+/);     // Regular expression match
P.oneOf('abc');         // Single character matching 'a', 'b', or 'c'
P.whitespace;           // One or more whitespace characters
P.optWhitespace;        // Zero or more whitespace characters
P.eof;                  // End of input stream

Combinators

// Sequence: matches all parsers in exact order
P.seq(P.string('('), P.number, P.string(')'));

// Alternatives: matches first successful parser
P.alt(P.string('true'), P.string('false'));
// or using .or():
a.or(b);

// Delimited / Separated lists
P.sepBy(P.number, P.string(','));  // Comma-separated numbers (zero or more)
P.sepBy1(P.number, P.string(',')); // Comma-separated numbers (at least one)

// Repetition
a.many();        // 0 or more
a.atLeast(1);    // 1 or more
a.times(3);      // Exactly 3 times
a.times(1, 4);   // Between 1 and 4 times

// Discarding tokens
a.skip(P.string(';')); // Parses 'a', matches ';', returns only 'a'

Transforming Output (map)

const arithmeticExpr = P.seq(
  P.digits.map(Number),
  P.oneOf('+-*/').trim(P.optWhitespace),
  P.digits.map(Number)
).map(([left, operator, right]) => ({
  type: 'BinaryExpression',
  operator,
  left,
  right
}));

arithmeticExpr.parse('10 + 20');
/*
{
  status: true,
  value: { type: 'BinaryExpression', operator: '+', left: 10, right: 20 }
}
*/

References

Related topics