LoginSignup
6

More than 3 years have passed since last update.

正規表現チートシート

Last updated at Posted at 2018-10-15

定型書式

PHPでは、スラッシュでパターンを囲む。

/パターン/

量指定子

ルール

* 0または1回以上の繰り返し
+ 1回以上の繰り返し
? 0または1回の繰り返し

<対象>
(1)ああ
(2)あ
(3)い

<パターン>
/あ+/

<結果>
(1),(2)がマッチ

指定回数の繰り返し

ルール

{1} 1回の繰り返し
{1,3} 1回以上3回以下の繰り返し
{1,} 1回以上の繰り返し
{,3} 3回以下の繰り返し

<対象>
(1)あ
(2)あああ
(3)ああああ

<パターン>
/あ{2,3}/

<結果>
(2)がマッチ

文字指定

ルール

. 任意の文字(なんでもok)
[A-Z] 大文字アルファベットを指定
[a-z] 小文字アルファベットを指定
[0-9] 数字を指定
[あ-んア-ン] 平仮名、カタカナを指定
[^0-9] 数字以外を指定

<対象>
(1)あい
(2)あい1
(3)あい1アイ

<パターン>
/[あ-んア-ン0-9]*/

<結果>
(3)がマッチ

特殊な意味を持つ表現

ルール

\w 単語構成語(記号以外)
\W 非単語構成語
\d 数字
\D 数字以外
\s 空白文字(スペースやタブ等)
\S 非空白文字
\b 単語区切り
\B 非単語区切り
\t タブ
\n 改行
\A 文頭
\z 文末
^ 行頭
$ 行末

<対象>
(1)5 あい
(2)あい 5
(3)5あい

<パターン>
/^\d{1,}\s[あ-ん]*/

<結果>
(1)がマッチ

PHPの正規表現を用いる関数

preg_match

http://php.net/manual/ja/function.preg-match.php
読み込ませた文字列にパターンとマッチするものがあるかを調べられる関数。

$arrs = array("イチゴ", "いちご", "ICHIGO");
foreach($arrs as $arr) {
  $result = $preg_match('/[A-Z]*/', $arr);
  echo $result . "\n";
}

# 結果
false
false
true

preg_replace

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
6