Multiple matches in a string using regex in bash

bash, bash4

Solution

OK so one way I did this is to put it in a for loop:

myString="DO-BATCH BATCH-DO"
for aString in ${myString[@]}; do
    if [[ ${aString} =~ ([[:alpha:]]*)-([[:alpha:]]*) ]]; then
     echo ${BASH_REMATCH[1]} #first perens
     echo ${BASH_REMATCH[2]} #second perens
     echo ${BASH_REMATCH[0]} #full match
    fi
done

which outputs:
DO
BATCH
DO-BATCH
BATCH
DO
BATCH-DO

Which works but I kind of was hoping to pull it all from one regex if possible.

Problem

Been looking for some more advanced regex info on regex with bash and have not found much information on it. Here's the concept, with a simple string: ``` myString="DO-BATCH BATCH-DO" if [[ $myString =~ ([[:alpha:]]*)-([[:alpha:]]*) ]]; then echo ${BASH_REMATCH[1]} #first perens echo ${BASH_REMATCH[2]} #second perens echo ${BASH_REMATCH[0]} #full match fi outputs: BATCH DO DO-BATCH ``` So fine it does the first match (BATCH-DO) but how do I pull a second match (DO-BATCH)? I'm just drawing a blank here and can not find much info on bash regex.

Original source