Ruby | Regexp named_captures() function

Regexp#named_captures() : named_captures() is a Regexp class method which returns a hash representing information about named captures of regular expression. A key of the hash is a name of the named capture produces a formatted string-version of the regular expression.

Syntax: Regexp.named_captures()

Parameter: Regexp values



Return: a hash representing information about named captures of regular expression

Example #1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby code for Regexp.named_captures() method
   
# declaring Regexp value
reg_a = /a/
   
# declaring Regexp value
reg_b = /geeks/
   
# declaring Regexp value
reg_c = /a/
   
   
#  named_captures method
puts "Regexp named_captures form : #{reg_a.named_captures}\n\n"
   
puts "Regexp named_captures form : #{reg_b.named_captures}\n\n"
   
puts "Regexp named_captures form : #{reg_c.named_captures}\n\n"

chevron_right


Output :

Regexp named_captures form : {}

Regexp named_captures form : {}

Regexp named_captures form : {}

Example #2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby code for Regexp.named_captures() method
  
# declaring Regexp value
reg_a = /geeks/
  
# declaring Regexp value
reg_b = /problem/
  
# declaring Regexp value
reg_c = /code/
  
  
#  named_captures method
puts "Regexp named_captures form : #{reg_a.named_captures}\n\n"
  
puts "Regexp named_captures form : #{reg_b.named_captures}\n\n"
  
puts "Regexp named_captures form : #{/(?<goio>.)(?<goio>.)/.named_captures}\n\n"

chevron_right


Output :

Regexp named_captures form : {}

Regexp named_captures form : {}

Regexp named_captures form : {"goio"=>[1, 2]}
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.