Tutorial by Examples

Ruby extends the standard group syntax (...) with a named group, (?<name>...). This allows for extraction by name instead of having to count how many groups you have. name_reg = /h(i|ello), my name is (?<name>.*)/i #i means case insensitive name_input = "Hi, my name is Zaphod Be...
if /hay/ =~ 'haystack' puts "There is hay in the word haystack" end Note: The order is significant. Though 'haystack' =~ /hay/ is in most cases an equivalent, side effects might differ: Strings captured from named capture groups are assigned to local variables only when Regexp#=~...
Quantifiers allows to specify count of repeated strings. Zero or one: /a?/ Zero or many: /a*/ One or many: /a+/ Exact number: /a{2,4}/ # Two, three or four /a{2,}/ # Two or more /a{,4}/ # Less than four (including zero) By default, quantifiers are greedy, whi...
Describes ranges of symbols You can enumerate symbols explicitly /[abc]/ # 'a' or 'b' or 'c' Or use ranges /[a-z]/ # from 'a' to 'z' It is possible to combine ranges and single symbols /[a-cz]/ # 'a' or 'b' or 'c' or 'z' Leading dash (-) is treated as charachter /[-a-c]/ # '-' or 'a' o...
You can test if a string matches several regular expressions using a switch statement. Example case "Ruby is #1!" when /\APython/ puts "Boooo." when /\ARuby/ puts "You are right." else puts "Sorry, I didn't understand that." end This w...
A Regexp can be created in three different ways in Ruby. using slashes: / / using %r{} using Regex.new #The following forms are equivalent regexp_slash = /hello/ regexp_bracket = %r{hello} regexp_new = Regexp.new('hello') string_to_match = "hello world!" #All of th...
Returns true or false, which indicates whether the regexp is matched or not without updating $~ and other related variables. If the second parameter is present, it specifies the position in the string to begin the search. /R.../.match?("Ruby") #=> true /R.../.match?("Ruby&quot...
Regular expressions are often used in methods as parameters to check if other strings are present or to search and/or replace strings. You'll often see the following: string = "My not so long string" string[/so/] # gives so string[/present/] # gives nil string[/present/].nil? # gives ...

Page 1 of 1