Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does BASH_REMATCH not work for a quoted regular expression?

Tags:

regex

bash

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?

like image 585
Hanfei Sun Avatar asked Sep 06 '25 03:09

Hanfei Sun


1 Answers

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
like image 133
Gilles Quenot Avatar answered Sep 07 '25 19:09

Gilles Quenot