Tbpgr Blog

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

書籍 Regular Expressions Cookbook | Group and Capture Parts of the Match

パンくず

書籍 Regular Expressions Cookbook
Group and Capture Parts of the Match

概要

複数用語を1つのグループとしてマッチさせる方法について。

構文

Groups(複数の候補の中から一つだけでも一致すればマッチ)
\b(one|two|three)\b
Noncapturing groups(グループでマッチした内容の参照を持たない)
\b(?:one|two|three)\b
Group with mode modifiers(大文字小文字不問かつ参照を持たない)
\b(?i:one|two|three)\b

サンプル

require "pp"

pp "hage 1234-55-78 hoge".gsub(/\b(\d\d\d\d)-(\d\d)-(\d\d)\b/,"yes!") #=>置換結果:"hage yes! hoge"
pp "hage 1234-552-78 hoge".gsub(/\b(\d\d\d\d)-(\d\d)-(\d\d)\b/,"yes!") #=>置換されない
pp "hage a234-55-78 hoge".gsub(/\b(\d\d\d\d)-(\d\d)-(\d\d)\b/,"yes!") #=>置換されない

# Group キャプチャあり
pp "Mary mary Jane jane Sue sue".gsub(/\b(Mary|Jane|Sue)\b/,"yes(\\1)") #=>置換結果:"yes(Mary) mary yes(Jane) jane yes(Sue) sue"
# Group キャプチャなし(パフォーマンス重視かつ、参照を利用しない場合)
pp "Mary mary Jane jane Sue sue".gsub(/\b(?:Mary|Jane|Sue)\b/,"yes!(\\1)") #=>置換結果:"yes!() mary yes!() jane yes!() sue"
# 大文字小文字区別なし キャプチャなし
pp "Mary mary Jane jane Sue sue".gsub(/\b(i:Mary|Jane|Sue)\b/,"yes!(\\1)") #=>置換結果:"Mary mary yes!(Jane) jane yes!(Sue) sue"