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?

More than 1 year has passed since last update.

正規表現一覧(ChatGPT依存)

Last updated at Posted at 2023-03-09

バックエンドでバリデーションを行うときにだいたい、そのフレームワークに存在するルールを使い、必要とあらばカスタムルールを作ると思います。
しかし、カスタムルールとか作っていくうちに「全部正規表現で実現したいな」と思ったのがこの記事を書くことになったきっかけになります。
テストをしてから載せていますが、用いる場合は各自テストを行ってから使用してください。
当該記事にて、発生する責任は負いかねます。
※間違っていたら指摘いただけると助かります

見なくていいよ

ほとんどのテストケースはPHP 7.4.3で実行しました。

test.php
<?php
$has_test_case = array
(
    "テストケース1",
    "テストケース2",
    "テストケースn"
);
$regex = "正規表現";
foreach ($has_test_case as $test_case) {
    if (preg_match($regex, $test_case)) {
        echo 'true' . ' : ' . $test_case;
    } else {
        echo 'false' . ' : ' . $test_case;
    }
    echo "\n";
}
?>

正規表現

ルール 正規表現
空文字 ^$
数字のみ(1回以上) ^\d+$
数字以外(1回以上) ^[^0-9]+$
特定文字が含む(例↓) .*[].*
(例1) Hello, World! (true) .*[H].*
(例2) Hello, World! (true) .*[eoj].*
(例3) Hello, World! (false) .*[j].*
ひらがな1文字以上 ※注1 /[\x{3040}-\x{309F}]+/u
ひらがなのみ ※注2 /^\p{Hiragana}+$/u
カタカナ ※注3 /[\x{30A0}-\x{30FF}]+/u
郵便番号(ハイフンなし) ^\d{7}$
郵便番号(ハイフンあり) ^\d{3}-\d{4}$
フリーダイヤル(ハイフンなし) ※注4 ^(0120|0800|0570|080|012)\d{7,8}$
(固定)電話番号(ハイフンあり) ^0\d{1,3}-\d{1,4}-\d{4}$
(携帯)電話番号(ハイフンあり) ^0[789]0-\d{4}-\d{4}$
ipv4 /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
ipv4(RFC 1918準拠) ※注5
・10.0.0.0 ~ 10.255.255.255
・172.16.0.0 ~ 172.31.255.255
・192.168.0.0 ~ 192.168.255.255
/^(?:10.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2}).(?:25[0-5]|2[0-4]\d|[01]?\d{1,2}).(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})|172.(?:1[6-9]|2\d|3[01]).(?:\d{1,2}|1\d{2}|2[0-4]\d|25[0-5]).(?:\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])|192.168.(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))$/

メールアドレスとか、ipv6とかまた機会があれば追加します。

参照サイト

注1の参考サイト
https://www.asahi-net.or.jp/~ax2s-KMTN/ref/unicode/u3040.html

注2の参考サイト
http://www.unicode.org/charts/PDF/U3040.pdf

注3の参考サイト
http://www.unicode.org/charts/PDF/U30A0.pdf

注4の参考サイト
https://ja.wikipedia.org/wiki/%E3%83%95%E3%83%AA%E3%83%BC%E3%83%80%E3%82%A4%E3%83%A4%E3%83%AB

注5の参考サイト
https://www.rfc-editor.org/rfc/rfc1918

0
0
2

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?