📗 正規表現での前方一致、前方不一致、後方一致、後方不一致
※ 前方一致、後方一致で登場するパーレン(丸括弧)はキャプチャグループとして機能しない
キャプチャグループの例
// パーレンの中身が`$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
参考
Author And Source
この問題について(📗 正規表現での前方一致、前方不一致、後方一致、後方不一致), 我々は、より多くの情報をここで見つけました https://qiita.com/heppokofrontend/items/9d17bce4c67858804154著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .