Technical
Useful Regex Examples

How to parse -h or—help from script input


ARGV[0] =~ /-\?|-h|--help/

How to check if you have Am Or Pm


>> m =  /([0-9]+) +([AP]M)/.match("12 AM")
=> #<MatchData:0xb743cb34>
>> puts " match 1: #{m[0]} match 2: #{m[1]} match 3: #{m[2]}" 
=> match 1: 12 AM match 2: 12 match 3: AM

How To Get exect match for the string

To get exact match you would need to use ^ (which means begining of the string) and $ (which means end of the string) charecters with the string in question in the middle.

"NARROWS" =~ /(^NARROWS$|^GOWANUS$)/

How to match and retrive values that received the match.

Let say I have the following string "CCF08-987*" and I want to break it in a following manner [CCF][08]-[987][*] Following is a regular expression to do that:

"CCF08-987*" =~ /([a-zA-Z]+)(\d[0-9])-(\d[0-9]*)(\*)/

And following is the way of how to retrieve the matching values:


>> $1
=> "CCF" 
>> $2
=> "08" 
>> $3
=> "987" 
>> $4
=> "*" 

Playing around with literals in Regexp

Its very often that you have to parse out the ‘star’ (*) charecter when receiving user’s search input. In my case based on whether star in the begining or end of the string I would have to do either more(>) or less(<)
sign. Following patterns should help u get the matches.

This expresion checks whether star(*) is present in your string

>> "123*" =~ /(\*)/
=> 3 #this is a place at which match was found (starting with 0)

This expression checks if star is at the end of the string


>> "123*" =~ /(\*)$/
=> 3

This expression checks if star is at the begining of the string


>> "*123" =~ /^(\*)/
=> 0
>> $1
=> "*" 
>> $'

How to negate the result

Sometimes you don’t want to process string if it has certain charecters. In this particular example code will return false if string starts and ends with either X or D.


((Regexp.escape(row[0]) =~ (/(^X$|^D$)/));$1).blank?