Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a named group exists in a MatchData object?

Tags:

regex

ruby

ruby-1.9.2-p180 :003 > result = "test string".match(/(?<mtch>test)/)
 => #<MatchData "test" mtch:"test"> 
ruby-1.9.2-p180 :011 > result["mtch"]
 => "test" 
ruby-1.9.2-p180 :012 > result["fail"]
IndexError: undefined group name reference: fail
    from (irb):12:in `[]'
    from (irb):12
    from /Users/jeremysmith/.rvm/rubies/ruby-1.9.2-p180/bin/irb:16:in `<main>'

There isn't a MatchData function for checking whether a named group exists. is there some other way to check?

like image 779
Jeremy Smith Avatar asked Apr 07 '11 18:04

Jeremy Smith


1 Answers

result.names.include? 'mtch'
# => true
result.names.include? 'fail'
# => false
like image 119
Mladen Jablanović Avatar answered Nov 02 '22 06:11

Mladen Jablanović