かすみん日記

暇なときに何か喋ります

【正規表現】先読みと後読みの違いを表で理解する

正規表現の先読みと後読みの違いを表で整理する。

日本語で説明聞いてもよくわからないので、表から法則性を読み取る作戦に出る。

肯定の方だけ。

検索対象文字列は以下で固定とする。

hello_world!!
分類 正規表現 一致文字列 先・後読みで取得した「位置」に@ 挿入
肯定先読み .*(?=world) hello_ hello_@world!!
肯定先読み (?=world).* world!! hello_@world!!
肯定後読み .*(?<=world) hello_world hello_world@!!
肯定後読み (?<=world).* !! hello_world@!!
非捕獲式集合 .*(?:world) hello_world hello_world!!
非捕獲式集合 (?:world).* world!! hello_world!!

これで法則性が何となくわかるはず?

参考

表で整理するという発想を参考にした。

qiita.com