Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Regexp | named_captures

概要

Regexp#named_captures

詳細

正規表現に含まれる名前付きキャプチャ(named capture)の情報を Hash で返却。
Hash のキーは名前付きキャプチャの名前で、値は index のリストを返却。

サンプルコード
require 'tbpgr_utils'


bulk_puts_eval binding, <<-EOS
/(?<name>.+?), (?<age>.+?)/.named_captures
/(?<name>.+?), (?<name>.+?), (?<age>.+?)/.named_captures
/(.+?), (.+?)/.named_captures
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

/(?<name>.+?), (?<age>.+?)/.named_captures               # => {"name"=>[1], "age"=>[2]}
/(?<name>.+?), (?<name>.+?), (?<age>.+?)/.named_captures # => {"name"=>[1, 2], "age"=>[3]}
/(.+?), (.+?)/.named_captures                            # => {}