Using grep is not cross-platform compatible, since -P/--perl-regexp is only available on GNU grep, not BSD grep.
Here is the solution using ripgrep:
$ rg -o "foobar (\w+)" -r '$1' <test.txt
bash
happy
As per man rg:
-r/--replace REPLACEMENT_TEXTReplace every match with the text given.
Capture group indices (e.g.,
$5) and names (e.g.,$foo) are supported in the replacement string.
Related: GH-462.