0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

(備忘)Ruby 正規表現チェック方法

0
Last updated at Posted at 2026-04-10

正規表現リファレンス

アンカー

文字列の特定の位置(例えば、文字列の始まりや終わり)を指定するために使用される正規表現の要素(メタ文字列)。

  • \A 文字列の先頭にマッチ
  • \Z 文字列の末尾にマッチ
  • \z 同上
example
# 文字列中の real にマッチする
/real/.match("surrealist") # => #<MatchData "real">

# real から始まる文字列にマッチ
/\Areal/.match("surrealist") # => nil
/\Areal/.match("realist") # => #<MatchData "real">

# real と完全一致する文字列にマッチ
/\Areal\Z/.match("realist") # => nil 
/\Areal\Z/.match("real") # => #<MatchData "real">

正規表現リテラル

sample
# / で囲まれた文字列は正規表現
# / の直後の文字は、オプション(例:/x … 空白無視、 /i … 大文字小文字区別しない、/o … 式展開)
/^Ruby the OOPL/
/Ruby/i
/my name is #{myname}/o

%記法

sample
# %r は「正規表現」を表す
%r|Ruby|
%r{Ruby}

Web 上のチェッカー:Rubular

注意

  • 上述の「%記法」には対応しておらず、飽くまで // で囲った場合の「正規表現リテラル」に対応している

使用例

スクリーンショット 2026-04-10 17.29.14.png

Rails Console でのチェック

sample
docker compose exec hoge rails console
regex = %r|\ARuby.*\z|

# Ruby から始まる文字列にマッチ
regex.match?('Ruby') # => true
regex.match?('Ruby だよ') # => true

# 大文字・小文字が区別される
regex.match?('ruby') # => false
0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?