Why does BASH_REMATCH not work for a quoted regular expression?

bash, regex

Solution

In your bash REGEX, you should remove quotes. That's why that doesn't work.

If you have space, I recommend to use this way :

#!/bin/bash
x='foo bar bletch'
if [[ $x =~ foo[[:space:]](bar)[[:space:]]bl(.*) ]]
then
    echo The regex matches!
    echo $BASH_REMATCH      
    echo ${BASH_REMATCH[1]} 
    echo ${BASH_REMATCH[2]} 
fi

Problem

The code is like this: ``` #!/bin/bash if [[ foobarbletch =~ 'foo(bar)bl(.*)' ]] then echo "The regex matches!" echo $BASH_REMATCH echo ${BASH_REMATCH[1]} echo ${BASH_REMATCH[2]} fi ``` When I try to run it, it doesn't display anything: ``` bash-3.2$ bash --version GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin12) Copyright (C) 2007 Free Software Foundation, Inc. bash-3.2$ /bin/bash test_rematch.bash bash-3.2$ ``` Does anyone have ideas about this?

Original source