Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

regex - Why does BASH_REMATCH not work for a quoted regular expression?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...