LoginSignup
4
5

More than 5 years have passed since last update.

Regexp.unionで正規表現を結合する

Posted at

最近知ったが非常に便利だと思った

REGEXP_INT = /\A\d+\Z/
REGEXP_EN  = /\A\w+\Z/

# 英数字のみ
p Regexp.union(REGEXP_INT, REGEXP_EN) =~ "123"     # => 0
p Regexp.union(REGEXP_INT, REGEXP_EN) =~ "abc"     # => 0
p Regexp.union(REGEXP_INT, REGEXP_EN) =~ "123abc"  # => 0
p Regexp.union(REGEXP_INT, REGEXP_EN) =~ "123-abc" # => nil

例えば正規表現のパターンを動的に配列に格納して使う事ができるので便利

# ある文字列から任意の単語を抽出する
str = "dog cat\npigdog mouse cat dog"
regexps = %w(dog cat).map {|s| Regexp.new(s)}

p str.scan(Regexp.union(*regexps))
# => ["dog", "cat", "dog", "cat", "dog"]

# おまけ(出現数カウント)
p str.scan(Regexp.union(*regexps)).group_by(&:itself).map{|k,v| [k.to_sym, v.size]}.to_h
# => {:dog=>3, :cat=>2}
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5