10
8

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.

Bash | 正規表現でマッチした文字列をキャプチャして使う

Last updated at Posted at 2016-07-14

$BASH_REMATCH を使えば良い。

string="--ABC--"
regexp="-(A)(B)(C)-"

if [[ $string =~ $regexp ]]
then
  echo ${BASH_REMATCH[0]} # => -ABC-
  echo ${BASH_REMATCH[1]} # => A
  echo ${BASH_REMATCH[2]} # => B
  echo ${BASH_REMATCH[3]} # => C
fi

説明

  • $BASH_REMATCH[0] には、キャプチャとは関係なく、マッチした文字列全体が入る。
  • $BASH_REMATCH[1] 以降には、キャプチャした順番で、マッチした文字列が入る。

ちなみに

正規表現部分を直書きするとダメで、いちど変数に収める必要があるっぽい。

string="--ABC--"

if [[ $string =~ "-(A)(B)(C)-" ]]
then
  echo ${BASH_REMATCH[0]}
  echo ${BASH_REMATCH[1]}
  echo ${BASH_REMATCH[2]}
  echo ${BASH_REMATCH[3]}
fi

環境

  • bash 3.2

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

10
8
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?