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
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:
BASH_REMATCH[]
so at this point I'm guessing this is the expected result?
characters in the regex