With POSIX-ly sedly sed, you can attain the required results for both scenarios, as shown:
w='[[:alpha:]][_[:alnum:]]*'
echo 'deploy-api-productionN' |
sed -n -e "/^\($w-\)\{0,1\}deploy-/s/^$w\(-\($w\)\)\{1,\}\$/\2/p"
Observations:
- since sed has no symbol for a word, we will build a regex for that and store them in shell variable $w
- \{0,11\} is BRE for ?
- \{1,\} is BRE for +
- \(...\) is BRE for (...)