Groups, named and otherwise
suggest changeRuby 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 Beeblebrox"
match_data = name_reg.match(name_input) #returns either a MatchData object or nil
match_data = name_input.match(name_reg) #works either way
if match_data.nil? #Always check for nil! Common error.
puts "No match"
else
match_data[0] #=> "Hi, my name is Zaphod Beeblebrox"
match_data[1] #=> "i" # the first group, (i|ello)
match_data[2] #=> "Zaphod Beeblebrox"
# A named group can also be read by name
match_data[:name] #=> "Zaphod Beeblebrox"
match_data["name"] #=> "Zaphod Beeblebrox"
puts "Hello #{match_data[:name]}!"
end
Index 0 is the whole match. Capturing groups start at 1, in the order of their opening parentheses:
reg = /(((a)b)c)(d)/
match = reg.match 'abcd'
match[0] #=> "abcd"
match[1] #=> "abc"
match[2] #=> "ab"
match[3] #=> "a"
match[4] #=> "d"
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents