📗 正規表現での前方一致、前方不一致、後方一致、後方不一致


※ 前方一致、後方一致で登場するパーレン(丸括弧)はキャプチャグループとして機能しない

キャプチャグループの例
// パーレンの中身が`$1`で参照できる状態
'abcdef'.replace(/(.*?)def/, '$1'); // -> abc

// パーレンの中身が`p1`で参照できる状態
'abcdef'.replace(/(.*?)def/, (_, p1) => {
  console.log(p1); // > abc

  return p1;
}); // -> abc

前方一致

特定の条件の後に続く文字列を探索したい。

(?<=●)

// abcに続く「def」を★にしたい
'abcdef'.replace(/(?<=abc)def/, '') // -> abc★
'abcDEF'.replace(/(?<=abc)def/, '') // -> abcDEF
'ABCdef'.replace(/(?<=abc)def/, '') // -> ABCdef
'123def'.replace(/(?<=abc)def/, '') // -> 123def

前方不一致

特定の条件以外の後に続く文字列を探索したい。

(?<!●)

// abc以外の文字列に続く「def」を★にしたい
'abcdef'.replace(/(?<!abc)def/, '') // -> abcdef
'abcDEF'.replace(/(?<!abc)def/, '') // -> abcDEF
'ABCdef'.replace(/(?<!abc)def/, '') // -> ABC★
'123def'.replace(/(?<!abc)def/, '') // -> 123★

後方一致

特定の条件が後に続く文字列を探索したい。

(?=●)

// defが後に続く「abc」を★にしたい
'abcdef'.replace(/abc(?=def)/, '') // -> ★def
'abcDEF'.replace(/abc(?=def)/, '') // -> abcDEF
'ABCdef'.replace(/abc(?=def)/, '') // -> ABCdef
'abc123'.replace(/abc(?=def)/, '') // -> abc123

後方不一致

特定の条件が後に続かない文字列を探索したい。

(?!●)

// defが後に続かない「abc」を★にしたい
'abcdef'.replace(/abc(?!def)/, '') // -> abcdef
'abcDEF'.replace(/abc(?!def)/, '') // -> ★DEF
'ABCdef'.replace(/abc(?!def)/, '') // -> ABCdef
'abc123'.replace(/abc(?!def)/, '') // -> ★123

参考