0
0

シェルスクリプト 正規表現の有効性検証方法

Posted at

概要

Goなどの高級言語で正規表現を使用する時には、正規表現が有効なものかどうか無意識にでも判別していると思います。

  • MustCompile
    • 正規表現が正しくない場合はプログラムを強制終了する
  • Compile
    • 正規表現が正しくない場合はエラーとなる

今回は、シェルスクリプトで正規表現が本当に正しい正規表現なのかチェックする方法について調べてみました。

grepコマンドを使用する方法

grepコマンドを使って正規表現が適用可能かどうかを確認できます。grepは正規表現が無効であればエラーメッセージを出力します。

#!/bin/bash

regex="$1"

# テスト文字列
test_string="test"

# 正規表現をテストするための関数
function test_regex {
    echo "$test_string" | grep -E "$regex" > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "正しい正規表現です。"
    else
        echo "無効な正規表現です。"
    fi
}

# 正規表現をテスト
test_regex

awkコマンドを使用する方法

awkも正規表現の有効性を確認するのに使えます。無効な正規表現の場合、エラーメッセージが表示されます。

#!/bin/bash

regex="$1"

# テスト文字列
test_string="test"

# 正規表現をテストするための関数
function test_regex {
    echo "$test_string" | awk -v regex="$regex" 'BEGIN { if (match("", regex)) exit 1 }'
    if [ $? -eq 0 ]; then
        echo "正しい正規表現です。"
    else
        echo "無効な正規表現です。"
    fi
}

# 正規表現をテスト
test_regex

perlコマンドを使用する方法

perlも正規表現の有効性をチェックするために使用できます。

#!/bin/bash

regex="$1"

# 正規表現をテストするための関数
function test_regex {
    perl -e "qr/$regex/" 2> /dev/null
    if [ $? -eq 0 ]; then
        echo "正しい正規表現です。"
    else
        echo "無効な正規表現です。"
    fi
}

# 正規表現をテスト
test_regex

sedコマンドを使用する方法

sedも正規表現の有効性を確認するために使えますが、sedの正規表現は若干の違いがあるため注意が必要です。

#!/bin/bash

regex="$1"

# テスト文字列
test_string="test"

# 正規表現をテストするための関数
function test_regex {
    echo "$test_string" | sed -E "s/$regex//" > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "正しい正規表現です。"
    else
        echo "無効な正規表現です。"
    fi
}

# 正規表現をテスト
test_regex
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