Parsing in Coffescript

Osvaldo Toja bio photo By Osvaldo Toja Comment

Parsing with regex is simple in coffescript. Just use the same syntax as Javascript as shown below.

More info here.

tl;dr

for your copy/paste please, just type the following on a coffee</console>.

string="wp-theme-acme-2.1.33.zip"
pattern = /^([a-z\-]*)-([\d\.]*).zip/
string.match(pattern)
[component,version] = string.match(pattern)[1...3]
component
version

Output

coffee> string="wp-theme-acme-2.1.33.zip"
'wp-theme-acme-2.1.33.zip'
coffee> pattern = /^([a-z\-]*)-([\d\.]*).zip/
/^([a-z\-]*)-([\d\.]*).zip/
coffee> string.match(pattern)
[ 'wp-theme-acme-2.1.33.zip',
  'wp-theme-acme',
  '2.1.33',
  index: 0,
  input: 'wp-theme-acme-2.1.33.zip' ]
coffee>

We can store the parsed results directly into variables using something like the following.

[component,version] = string.match(pattern)[1...3]

Output

coffee> [component,version] = string.match(pattern)[1...3]
[ 'wp-theme-acme', '2.1.33' ]
coffee> component
'wp-theme-acme'
coffee> version
'2.1.33'
coffee>
comments powered by Disqus