Published in: Groovy
|
|
|
URL: http://hansamann.podspot.de/files/grails_podcast_episode_32_1036.mp3
This snippet gives you some interesting examples what you can do with Strings and GStrings in Groovy. Listen to the audio to get the best learning experience. Simply right-click on the title above -> Save as... to download the mp3 file of this part of the series.
The Groovy Series is part of the Grails Podcast and can be subscribed to via: http://hansamann.podspot.de/rss. The series is produced by Dierk König and Sven Haiges, further information about the topic of this episode can be found in the book
Groovy in Action - http://groovy.canoo.com/gina
//regex patterns look strange, but groovy makes them look better //use slashy syntax to declare a pattern, get rid of double-esacping //example below both defines the same pattern to match a time like 15:01 //find a string, return true if found, false otherwise //note, you can easily use this for branching def timeRegex = /\d\d:\d\d/ //calling matcher.find() finds the first occurrence, then steps to the next if called again //notice we used a regex group in the pattern: /(\d\d:\d\d)/ { } //a more groovy way to the same thing as above, eachMatch method in String //note: no grouping parentheses needed in regex! /\d\d:\d\d/ } //using groups with the matcher and each closure. Within the pattern, we can use GString replacements to make //the pattern readable def DATE = /\d\d.\d\d.\d\d\d\d/ def TIME = /\d\d:\d\d/ ("Today is 31.01.2007, 15:01. Tomorrow is 01.02.2007, 15:01" =~ /($DATE), ($TIME)/).each { all, date, time -> dates << date }
Comments
Subscribe to comments
You need to login to post a comment.
Hmmm interesting.
I changed line 41 to have one more group in the regex, and the code failed at runtime. Then when I added another parameter to the closure, it worked. The number of parameters expected in the closure are num_groups + 1. We need one more for the 'all' (which I guess must be holding all the groups of that match).
Thanks for the tutorial.