Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

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}
ryosukeA
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away