Just do IT

思うは招く

正規表現の \b を使ってピンポイントで単語をマッチさせる

やりたいこと

以下の文章から、onという文字だけを抜き出したい。

I have a dream that one day on the red hills of Georgia, the sons of former slaves and the sons of former slave owners will be able to sit down together at the table of brotherhood.

解決

\bon\bという正規表現を使うと抜き出せる。

f:id:K_Koh:20201112175341j:plain

Rubular: a Ruby regular expression editor

onにしても、「one」や「sons」などもヒットしてしまう。

f:id:K_Koh:20201112175223j:plain

\bは単語の境界を表す。単語の前後といった位置にマッチしている。つまり今回の場合、「直前と直後に境界がある、onとマッチさせる」という意味になる。

参考

qiita.com