Ohm/JS CSV Example
A simple Ohm grammar for parsing CSV data.
by Patrick Dubroy
HTML
<script src="https://unpkg.com/ohm-js@16/dist/ohm.min.js"></script>
<pre id="result"></pre>
JavaScript
// An Ohm grammar for parsing CSV (comma-separated value) data.
// Syntax reference: https://github.com/harc/ohm/blob/master/doc/syntax-reference.md
const grammarSource = String.raw`
CSV {
csv = row (eol ~end row)* eol?
row = col ("," col)*
col = colChar*
colChar = ~(eol | ",") any
eol = "\r"? "\n"
}
`;
// Instantiate the grammar defined above.
const g = ohm.grammar(grammarSource);
const csvInput = [
'VTSMX,13,108.82,1305.84',
'VGTSX,30,40.20,1206.00',
'VBMFX,204,10.67,2176.68'
].join('\n');
const m = g.match(csvInput);
const result = m.succeeded() ? 'Match succeeded' : 'Match failed: ' + m.message;
document.getElementById('result').textContent = result;