I usually use PCRE mode and prepend what I want to be displayed with `\K` (and append a lookahead if needed):
~ $ echo "foo bar1 baz foo bar2" | grep -oP 'foo \Kbar\d'
bar1
bar2
~ $ echo "foo bar1 baz foo bar2" | grep -oP 'foo \Kbar\d(?= baz)'
bar1
~ $ echo "foo bar1 baz foo bar2" | grep -oP 'foo \Kbar\d(?=$)'
bar2
Of course, it implies using a version of `grep` supporting the `-P` option. Notably, MacOS doesn't by default, although if -P is utterly needed, there are ways to install gnu-grep or modify the command used to achieve the same result.
Your way is perhaps more cross-platform, but for my (very personal) use cases, mine is easier to remember and needs no setup.Edit: worst case, piping to `cut` or `awk` can also be a solution.