Date parsing

87 views
Skip to first unread message

Paul McGuinness

unread,
Oct 3, 2016, 10:57:39 AM10/3/16
to PEG.js: Parser Generator for JavaScript
Hi All,

I'm trying to add some basic NLP to my web-based reporting application and PEG looks like the best way to go. I've come up with the following syntactical tree for requesting reports, but I'm not great with RegEx and wondered about the best way to accept date/times in the following formats:-


yyyy-dd-mm
yy-dd-mm
dd/mm/yyyy hh:mm:ss
dd/mm/yyyy hh:mm
dd/mm/yyyy
hh:mm 


Any help greatly appreciated....

Cheers,

Paul


start
  = item+

item
  = action object target date
  
action
  = action:('find'/'report'/'compare'/'stdev') ? __  { return {action:action}; }

object
  = object:('extn'/'extension'/'trunk'/'console') _ { return {object:object}; }

target
  = exp:[a-zA-Z0-9]+ __ ? { return {target:exp.join('')}; }

date
 = date:('today'/'yesterday'/'last week'/'this week'/'last month'/'this month') __ ? { return {date:date}; }

// optional whitespace
_  = [ \t\r\n]*

// mandatory whitespace or delimitation
__ = [ \t\r\n,;"or"]+

David Majda

unread,
Oct 11, 2016, 9:15:03 AM10/11/16
to paul.d.m...@gmail.com, PEG.js: Parser Generator for JavaScript
2016-10-03 16:57 GMT+02:00 Paul McGuinness <paul.d.m...@gmail.com>:
I'm trying to add some basic NLP to my web-based reporting application and PEG looks like the best way to go. I've come up with the following syntactical tree for requesting reports, but I'm not great with RegEx and wondered about the best way to accept date/times in the following formats:-


yyyy-dd-mm
yy-dd-mm
dd/mm/yyyy hh:mm:ss
dd/mm/yyyy hh:mm
dd/mm/yyyy
hh:mm 

The most straightforward way is probably to define a rule for each format and then use a choice operator to select a matching one:

Date
  = DateYYYYDDMM
  / DateYYDDMM
  // ...

DateYYYYDDMM
  = year:YYYY "-" day:DD "-" month:MM {
      return new Date(year, month - 1, day);
    }

DateYYDDMM
  = year:YY "-" day:DD "-" month:MM {
      return new Date(year, month - 1, day);
    }

// ...

YYYY
  = Digit Digit Digit Digit { return parseInt(text(), 10); }

YY
  = Digit Digit { return parseInt(text(), 10); }

MM
  = Digit Digit { return parseInt(text(), 10); }

DD
  = Digit Digit { return parseInt(text(), 10); }

Digit
  = [0-9]

Another approach would be to parse dates using a library such as moment-parser. This particular library is in fact implemented using PEG.js internally, so you can have a look how date parsing is done there.

--
David Majda
http://majda.cz/

Paul McGuinness

unread,
Oct 13, 2016, 5:21:49 AM10/13/16
to PEG.js: Parser Generator for JavaScript, paul.d.m...@gmail.com
Many thanks! Exactly what I needed :-)
Reply all
Reply to author
Forward
0 new messages