0

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

3
  • 2
    please update the question to show the expected contents of BASH_REMATCH[] Commented Nov 3, 2024 at 21:24
  • 3
    You need to escape the special characters | and * as they are not interpreted literally. Try regex='([[:digit:]]+)?\|([[:digit:]])\*;\[([[:digit:]]+)?;STOP;([[:digit:]]+)?;' Commented Nov 3, 2024 at 21:29
  • To make it much easier, you can add this to replace all non-numbers with a space: RESULT="${RESULT//[!0-9]/ }" Commented Nov 3, 2024 at 21:51

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.