bash regex with quotes?

后端 未结 4 2150
走了就别回头了
走了就别回头了 2020-11-22 12:53

The following code

number=1
if [[ $number =~ [0-9] ]]
then
  echo matched
fi

works. If I try to use quotes in the regex, however, it stops:

4条回答
  •  天命终不由人
    2020-11-22 13:48

    GNU bash, version 4.2.25(1)-release (x86_64-pc-linux-gnu)

    Some examples of string match and regex match

        $ if [[ 234 =~ "[0-9]" ]]; then echo matches;  fi # string match
        $ 
    
        $ if [[ 234 =~ [0-9] ]]; then echo matches;  fi # regex natch 
        matches
    
    
        $ var="[0-9]"
    
        $ if [[ 234 =~ $var ]]; then echo matches;  fi # regex match
        matches
    
    
        $ if [[ 234 =~ "$var" ]]; then echo matches;  fi # string match after substituting $var as [0-9]
    
        $ if [[ 'rss$var919' =~ "$var" ]]; then echo matches;  fi   # string match after substituting $var as [0-9]
    
        $ if [[ 'rss$var919' =~ $var ]]; then echo matches;  fi # regex match after substituting $var as [0-9]
        matches
    
    
        $ if [[ "rss\$var919" =~ "$var" ]]; then echo matches;  fi # string match won't work
    
        $ if [[ "rss\\$var919" =~ "$var" ]]; then echo matches;  fi # string match won't work
    
    
        $ if [[ "rss'$var'""919" =~ "$var" ]]; then echo matches;  fi # $var is substituted on LHS & RHS and then string match happens 
        matches
    
        $ if [[ 'rss$var919' =~ "\$var" ]]; then echo matches;  fi # string match !
        matches
    
    
    
        $ if [[ 'rss$var919' =~ "$var" ]]; then echo matches;  fi # string match failed
        $ 
    
        $ if [[ 'rss$var919' =~ '$var' ]]; then echo matches;  fi # string match
        matches
    
    
    
        $ echo $var
        [0-9]
    
        $ 
    
        $ if [[ abc123def =~ "[0-9]" ]]; then echo matches;  fi
    
        $ if [[ abc123def =~ [0-9] ]]; then echo matches;  fi
        matches
    
        $ if [[ 'rss$var919' =~ '$var' ]]; then echo matches;  fi # string match due to single quotes on RHS $var matches $var
        matches
    
    
        $ if [[ 'rss$var919' =~ $var ]]; then echo matches;  fi # Regex match 
        matches
        $ if [[ 'rss$var' =~ $var ]]; then echo matches;  fi # Above e.g. really is regex match and not string match
        $
    
    
        $ if [[ 'rss$var919[0-9]' =~ "$var" ]]; then echo matches;  fi # string match RHS substituted and then matched
        matches
    
        $ if [[ 'rss$var919' =~ "'$var'" ]]; then echo matches;  fi # trying to string match '$var' fails
    
    
        $ if [[ '$var' =~ "'$var'" ]]; then echo matches;  fi # string match still fails as single quotes are omitted on RHS 
    
        $ if [[ \'$var\' =~ "'$var'" ]]; then echo matches;  fi # this string match works as single quotes are included now on RHS
        matches
    

提交回复
热议问题