LoginSignup
0
0

More than 1 year has passed since last update.

とりあえず、正規表現っぽいものを集めてみた

Posted at

正規表現とは

文字列の検索パターンを表現するための記号

正規表現の文字

  • リテラル :検索パターンで文字そのものを使う

  • メタ文字 :特殊な記号で高度な検索ができる

・「.」 → 改行を除く任意の1文字

Sample
# メタ文字
# .at
bat cat hat jet

・「\」 → メタ文字のエスケープ記号

Sample
# エスケープ
# \.
This is a pen.

文字種を限定したい場合
・「\d」 → デジットの略、0-9の1文字
・「\D」 → 数字以外の文字
・「\w」 → ワードの略、a-z,A-Z,0-9,_の1文字
・「\W」 → アルファベット、アンダーバー、数字以外の文字
・「\s」 → スペース、タブ、改行など
・「\S」 → 全ての非空白文字
量指定子
・「{n}」 → n個
・「{min,max}」 → min以上、max以下
・「{min,}」 → min以上
・「?」 → {0,1} 0以上1文字以下の繰り返し
・「+」 → {1,} 1文字以上の繰り返し
・「*」 → {0,} 0文字以上の繰り返し

Sample
# 文字種限定・量指定子
# \d\d-\d\d\d\d-\d\d\d\d or \d{2}-\d{4}-\d{4}
# h\w\w\w\w\w\w or h\w{6}
seki, 03-3001-1256
hidaka, 03-3015-3222
hayashi, 03-3017-7889

# \d{2}-?\d{4}-?\d{4}
03-3001-1256
0330011256
# \w+\d{2}-?\d{4}-?\d{4}
# \w*\d{2}-?\d{4}-?\d{4}
TEL03-3001-1256
T0330011256

# 最長マッチ、最短マッチ
# ".+" or ".+?"
"apple", "apples", "pineapple"

アンカー(位置指定)
・「^」 → キャレット、行の先頭
・「$」 → ダラーマーク、行の末尾
・「\b」 → バウンダリーの略、単語の境界

Sample
# アンカー
# ^\d \d$
# \bseki\b
1 taguchi 6
2 fkoji 9
3 seki 8
4 sekiya 7

選択子
・「abc|123」 → abc or 123

Sample
# 選択子
# example\.(net|com)
example.net
example.com

文字クラス
・「[abc]」 → a,b,cのどれか1文字

Sample
# 文字クラス
# (b|c|h)at
# [bch]at
bat cat hat

文字クラス内で使えるメタ文字
・「^」 → 否定 ※[の直後に配置
・「-」 → 範囲 ※文字コード表の順番に注意
image.png

Sample
# 文字クラス 範囲
# [A-F]\d+
A1
Q31
N18
C5
E32
L4

文字クラス[]内のエスケープルール
・「^」「-」「]」「\」はエスケープが必要
・「^」は[の直後でなければ、リテラルとして扱われる
・「-」は前に文字がなければ、リテラルとして扱われる

Sample
#文字クラス エスケープ
# ^\d{2}[\^\-.]
# ^\d{2}[-.^]\d{4}[-.^]\d{4}$
03^3015^3222
03-3015-3222
03.3015.3222

改行とタブ
・「\t」 → タブ
・「\r\n」 → 改行(Windows)
・「\r」 → 改行(v9までのmacOS)
・「\n」 → 改行(Unix、v10以降のmacOS)
・「\r\n|\r|\n」 → 改行(すべて)

Sample
# 改行とタブ
# \n+
a
bb
cc

cc

キャプチャ
・「()」 → $1,$2,...

Sample
# キャプチャ
# (.+),\s?(.+)
dotinstall, https://dotinstall.com
google,https://google.com
example, https://example.com
<a href="https://dotinstall.com">dotinstall</a>
<a href="https://google.com">google</a>
<a href="https://example.com">example</a>

後方参照
・「\1,\2,...」

Sample
# 後方参照
# (\d),\s\1
3, 8, 5, 4, 4, 5, 4, 1, 1, 5, 3, 3
0
0
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
0
0