Optimum grammar for expressions in strings

34 views
Skip to first unread message

Lachlan McDonald

unread,
May 25, 2018, 1:23:35 AM5/25/18
to PEG.js: Parser Generator for JavaScript
Hi everyone,

    I'm trying to find the formal\acceptable method for finding patterns within a group of otherwise unimportant information. For example to find ${i} within a string, where n is some integer.

The grammar looks quite verbose:

Pattern
    = (Plain Integer Plain)*
    
Plain
    = $(!'${'.)* { return "<String>" }
   
Integer
    = '${' v:$([0-9]+) '}' { return parseInt(v, 10); }
 

Which for the input:

abc ${1}${2} xyz ${3}

Will output:

[
   [
      "<String>",
      1,
      "<String>"
   ],
   [
      "<String>",
      2,
      "<String>"
   ],
   [
      "<String>",
      3,
      "<String>"
   ]
]

Where as this would be far more preferable:

[
   "<String>",
   1,
   "<String>",
   2,
   "<String>",
   3,
   "<String>"
]

Any and all suggestions are welcome.

jas...@snmpstack.com

unread,
Jun 4, 2018, 10:24:30 AM6/4/18
to PEG.js: Parser Generator for JavaScript
this is about a close as your going to get I think

Pattern
    = (Plain / Integer)*
    
Plain
    = $(!'${'.)+ { return "<String>" }
   
Integer
    = '${' v:$([0-9]+) '}' { return parseInt(v, 10); }

given the provided input 

gives 
[
   "<String>",
   1,
   2,
   "<String>",
   3
]

If you change Plain to : $(!'${'.)* { return "<String>" } you will get a potential infinite loop detected due to the fact it could match nothing forever.....
Reply all
Reply to author
Forward
0 new messages