Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a Ruby switch statement (case...when) with regex and backreferences?

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.

like image 477
Yuval Karmi Avatar asked Jul 23 '11 22:07

Yuval Karmi


People also ask

Can you use regex in switch statement?

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.

What does =~ mean in Ruby regex?

=~ 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.

Can I use regex in switch case JavaScript?

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).

What kind of regex does Ruby use?

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.


1 Answers

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 
like image 133
Yossi Avatar answered Nov 11 '22 16:11

Yossi