Why does BASH_REMATCH not work for a quoted regular expression?

前端 未结 3 1911
别那么骄傲
别那么骄傲 2020-11-30 06:51

The code is like this:

#!/bin/bash
if [[ foobarbletch =~ \'foo(bar)bl(.*)\' ]]
 then
     echo \"The regex matches!\"
     echo $BASH_REMATCH
     echo ${BAS         


        
相关标签:
3条回答
  • 2020-11-30 07:06

    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
    
    0 讨论(0)
  • 2020-11-30 07:14

    You can also assign the quoted regexp to a variable:

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

    This not only supports simple quoting but gives the regexp a name which can help readability.

    0 讨论(0)
  • 2020-11-30 07:19

    Thanks to your debugging statement, echo The regex matches!, you should have noticed there is no problem with BASH_REMATCH, since the if statement evaluates to false.

    In bash, regular expressions used with =~ are unquoted. If the string on the right is quoted, then it is treated as a string literal.

    If you want to include whitespaces in your regex's, then use the appropriate character classes, or escape your space if you want a space.

    0 讨论(0)
提交回复
热议问题