Partial string literals

49 views
Skip to first unread message

mike.p...@gmail.com

unread,
Dec 2, 2012, 4:05:51 PM12/2/12
to pe...@googlegroups.com
What's the easiest way to accept a partial string literal?

For example, I currently have rules like this one, that matches 'p', 'pr', 'pro' or 'prod'.

prod
= 'p'i ('r'i ('o'i ('d'i)?)?)? { return 'prod'; }

Is there a more general way of doing this? It's rather painful to maintain for anything more than a 3 or 4 character literal.

Zak Greant

unread,
Dec 2, 2012, 7:08:53 PM12/2/12
to mikepi...@gmail.com, pe...@googlegroups.com
Hi Mike,
It might be easiest to do the matching in Javascript. For example:

{
// return an array of words that match prefix str
function lookup(str){
var words = ['alpine', 'apple', 'apricot'];

return words.filter( function(word){
return word.indexOf( str ) === 0;
});
}
}

start
= str:[a-z]i+ { return lookup( str.join('') ); }

Cheers!
--zak

Scott Noel-Hemming

unread,
Dec 2, 2012, 9:03:39 PM12/2/12
to pe...@googlegroups.com
Depending on the surrounding rules I would think this would also work:

prod
= ( 'prod' / 'pro' / 'pr' / 'p' ) { return 'prod'; }

--
() ascii ribbon campaign - against html e-mail
/\ www.asciiribbon.org - against proprietary attachments

David Majda

unread,
Dec 4, 2012, 2:48:57 AM12/4/12
to mikepi...@gmail.com, pegjs
2012/12/2 <mike.p...@gmail.com>:
While there are some alternatives (as pointed out by others), there
isn't a non-painful way to do this in PEG.js, short of using some
templating engine to create rules like this mechanically or generating
the grammar from some source data.

What exactly are you trying to accomplish?

--
David Majda
Entropy fighter
http://majda.cz/
Reply all
Reply to author
Forward
0 new messages