0

I'm playing around with PEG.js

How can I allow to enter exactly 2 letters?

This is my approach:

start = word 
word = [A-Za-z]{2}

I used the {2} from regex, but unfortunately it doesn't work with PEG.js.

Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • 2
    Something like `{ // function twoLetterWord(o) { // if (o.length == 2) { // return o // } // else fail; // } // } // // start = word // word "word" // = word:[A-Za-z]+ { return twoLetterWord(word); }`? I could not find a way to fail the parser manually though. :( – Wiktor Stribiżew Oct 30 '15 at 15:06
  • If I am not mistaken to throw an error you use: error("error message"). You can also pass the location() field into it (it will contain it by default either way). – Ricardo Ferreira da Silva Jul 04 '18 at 08:45

2 Answers2

2

You can specify a letter class, then use two letters for your word. Although the syntax isn't pretty, I couldn't find another way in the documentation.

start = word
word = letter letter
letter = [A-Za-z]
thibpat
  • 714
  • 5
  • 17
  • You can add `i` after the closing square bracket to match case-insensitively. Also, you *could* duplicate the letter class, although it isn't very pretty: `[a-z]i [a-z]i`. – Toothbrush Nov 04 '15 at 18:14
0

As far as I see it you can use two options. The first option accepts only a word with two letters.

start = word 
word = [A-Za-z][A-Za-z]

This second option does some post-processing in javascript.

start = word 
word = word:([A-Za-z]+)
{
    if(word.length != 2) error("Word does not have two letters);
    else return word;
}