I know that I can write a Ruby case statement to check a match against a regular expressions. However, I'd like to use the match data in my return statement. Something like this semi-pseudocode:
foo = "10/10/2011" case foo when /^([0-9][0-9])/ print "the month is #{match[1]}" else print "something else" end
How can I achieve that?
Thanks!
Just a note: I understand that I wouldn't ever use a switch statement for a simple case as above, but that is only one example. In reality, what I am trying to achieve is the matching of many potential regular expressions for a date that can be written in various ways, and then parsing it with Ruby's Date class accordingly.
The -Regex parameter allows switch statements to perform regular expression matching against conditions. Output: One or more non-digits Any single char. Anchors and one or more word chars.
=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.
JavaScript actually allows the cases to be any object so Regular Expressions there are perfectly valid (unlike in many other languages where what you can use as the case is more limited). It may be “valid”, but it doesn't appear to actually work (at least not in Firefox, anyway).
A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.
The references to the latest regex matching groups are always stored in pseudo variables $1
to $9
:
case foo when /^([0-9][0-9])/ print "the month is #{$1}" else print "something else" end
You can also use the $LAST_MATCH_INFO
pseudo variable to get at the whole MatchData
object. This can be useful when using named captures:
case foo when /^(?<number>[0-9][0-9])/ print "the month is #{$LAST_MATCH_INFO['number']}" else print "something else" end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With