Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash regex using BASH_REMATCH not capturing all groups

In bash, I’m trying to capture this groups with this regex but BASH_REMATCH give me empty results

RESULT="1730624402|1*;[64452034;STOP;1730588408;74;22468;1"
regex="([[:digit:]]+)?|([[:digit:]])*;\[([[:digit:]]+)?;STOP;([[:digit:]]+)?;"

if [[ "$RESULT" =~ $regex ]]
    then
        echo "${BASH_REMATCH}"     # => 1730624402
        echo "${BASH_REMATCH[1]}"  # => 1730624402
        echo "${BASH_REMATCH[2]}"  # EMPTY
        echo "${BASH_REMATCH[3]}"  # EMPTY
        echo "${BASH_REMATCH[4]}"  # EMPTY
    else
        echo "check regex"
    fi

Where I go wrong?

Thanks in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

RESULT contains the literal characters | and *. These two characters have special meaning in regex’s so they need to be escaped. (NOTE: [ also has special meaning but OP has correctly escaped it.)

One modification to OP’s regex:

regex="([[:digit:]]+)\|([[:digit:]])\*;\[([[:digit:]]+);STOP;([[:digit:]]+);"
                     ^^             ^^
###########
# a shorter alternative:

regex="([0-9]+)\|([0-9])\*;\[([0-9]+);STOP;([0-9]+);"
               ^^       ^^

Taking for a test drive:

[[ "$RESULT" =~ $regex ]] && typeset -p BASH_REMATCH

declare -a BASH_REMATCH=([0]="1730624402|1*;[64452034;STOP;1730588408;" [1]="1730624402" [2]="1" [3]="64452034" [4]="1730588408")

NOTES:

  • OP hasn’t (yet) stated the desired contents of BASH_REMATCH[] so at this point I’m guessing this is the expected result
  • in this particular case I don’t see the need for the additional ? characters in the regex
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading