サンプルコード
str = "stringabcdefg---ff"
p str.scan(/a/)
p str.scan(/h/)
# .
# なんでもいい一文字
p str.scan(/.a/)
p str.scan(/..a/)
p str.scan(/..a./)
# ^
# 行の先頭
p str.scan(/^str/)
p str.scan(/^tr/)
# $
# 行の最後
p str.scan(/fg$/)
# *
# ワイルドカード、直前の文字が無い or 直前の文字が1個以上連続する
p str.scan(/g*/)
p str.scan(/-*/)
# +
# 最低1個は直前の文字が連続する
p str.scan(/g+/)
p str.scan(/-+/)
# ?
# 直前の文字が無い or 1つだけある
p str.scan(/g?/)
p str.scan(/-?/)
# .*
# なんでもいい文字の連続
p str.scan(/gab.*/)
# |
# 区切られた文字のいずれか
p str.scan(/a|f/)
# []
# []で括られた文字のどれか
p str.scan(/[af]/)
######### do end
str.scan(/[af]/) do |matched|
p matched
end
実行結果
/home/kure/.rbenv/versions/2.5.0/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /home/kure/mml-search/crawler/scan_test.rb
["a"]
[]
["ga"]
["nga"]
["ngab"]
["str"]
[]
[]
["", "", "", "", "", "g", "", "", "", "", "", "", "g", "", "", "", "", "", ""]
["", "", "", "", "", "", "", "", "", "", "", "", "", "---", "", "", ""]
["g", "g"]
["---"]
["", "", "", "", "", "g", "", "", "", "", "", "", "g", "", "", "", "", "", ""]
["", "", "", "", "", "", "", "", "", "", "", "", "", "-", "-", "-", "", "", ""]
["gabcdefg---ff"]
["a", "f", "f", "f"]
["a", "f", "f", "f"]
"a"
"f"
"f"
"f"
参考
Ruby 正規表現のまとめ - Qiita https://qiita.com/agotoh/items/87960d256e427d5673a9
サルにもわかる正規表現入門 http://www.mnet.ne.jp/~nakama/