8
5

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

bashで正規表現 ある文字列を含んである文字列を含まない

Posted at

やりたかったこと

"hoge"という文字列を含んで、"fuga"という文字列を含まないものを正規表現でマッチさせたかった。

ハマった点

以下で実行してみると「NG」となり、ハマって同僚に相談。

NAME="hoge"
if [[ ${NAME} =~ ^(?!.*fuga).*(?=hoge).* ]]; then
    echo "OK"
else
    echo "NG"
fi

どうやらbashの正規表現がEREなのでこれではうまくマッチしなかったのが原因。

対処

NAME="hoge"
MATCH_PATTERN="^.*hoge.*$"
MISMATCH_PATTERN="^.*fuga.*$"
if [[ ${NAME} =~ ${MATCH_PATTERN} && ! ${NAME} =~ ${MISMATCH_PATTERN} ]];then
    echo "OK"
else
    echo "NG"
fi

普通に一つずつ判断してAかつBって感じで判断してもらうようにしました。

8
5
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
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?