2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

正規表現について

Posted at

学習後の結論

100%理解し扱うのは今のところかなり難しい。

サービスやアプリの規模の大きさでも正規表現の目指す精度も違うだろうし、調べてみると様々な書き方があるので。

なので、参考リンクをベースに基本を習得し、ある程度噛み砕けるようになる。
そして、今後応用できるように情報をストックしておくのが今はベターかと思う。

参考リンク

https://qiita.com/jnchito/items/893c887fbf19e17d3ff9
https://qiita.com/teinen_qiita/items/806aba936a8ed1f7654e

正規表現(Regular Expression)とは

(regexとも呼ばれる)
文字列のパターンを指定して、指定した(有効な)文字列のみをマッチさせ、それ以外(無効な)の文字列はマッチしないようにする言語。置き換えも可。
(と、自分は認識)

メタ文字

正規表現で使用する特殊文字をメタ文字と呼ぶ。

基本的なメタ文字

.←なんでもいい一文字を検索。
^←先頭の文字を検索。
$←行の最後の文字を検索。
[]←この中で括られた一文字を検索。
*←直前の文字が0か1文字以上。
+←直前の文字が1文字以上。
?←直前の文字が0か1文字。
|←どちらか検索。(or)
()←この中に括られた全てを検索。

※メタ文字でなく、普通の文字としてマッチさせたい場合は\を前に付ける。
\. \^ \$ \[ \] \* \+ \? \| \( \)

その他のメタ文字

{n,m}{n}←文字の個数を限定。(文字量を指定するから「量指定子」 と呼ばれる)
\d←1個の半角数字(0123456789)を意味する。
\w←英単語を構成する文字を意味する。
\s←半角スペースやタブ文字\t、改行文字\tなど、目に見えない「空行文字全般」を意味する。(文字クラスと呼ばれる)
その他、復帰文字\rや改ページ文字fがある。

正規表現を試せるWebサイト

Rubular

使用例

自分のオリジナルアプリ内で、URL等にバリデーションをかける際に使用。

app/models/court.rb
class Court < ApplicationRecord
    belongs_to :user
     
    validates :store_name, presence: true

    VALID_TEL_REGEX = /0[1-9]\d{0,3}[-(]\d{1,4}[-)]\d{4}/
    validates :tel, format: { with: VALID_TEL_REGEX }, allow_blank: true

    VALID_EMAIL_REGEX = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
    validates :store_email, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX },
                                allow_blank: true
                      
    validates :url, format: { with: /\A^https?:\/\// }, allow_blank: true            
end
2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?