1
1

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 3 years have passed since last update.

bash上で正規表現を使って文字列の後方一致をチェックする

Posted at

bash上で正規表現を使って文字列の後方一致をチェックする際の備忘メモ

例えばURLがhttps://github.com/xxxx/testである事を確認したい場合でも、
以下のようにすると後方が一致してないのに一致と判定されてしまう。

test.sh
VALUE_URL="https://github.com/xxxx/test2"
if [[ "$VALUE_URL" =~ "http".*"://github.com/".*"test" ]]; then
    echo "OK"
else
    echo "NG"
fi
$ bash test.sh
OK

正規表現で後方一致をチェックする場合は、$を付ける。
(これは正規表現的に終端を意味するようだが、、どの仕様に基づくものか分からなかった。ご存知の方がおられれば教えてほしいです。)

test.sh
VALUE_URL="https://github.com/xxxx/test2"
if [[ "$VALUE_URL" =~ "http".*"://github.com/".*"test"$ ]]; then
    echo "OK"
else
    echo "NG"
fi
$ bash test.sh
NG

参考

正規表現:前方一致・後方一致・部分一致(〜を含む)の表現
【Shell】 シェルで部分一致(前方一致・後方一致)
Linuxで使う正規表現についてまとめました
BASH

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?