case1
i="text stack"
j="tex"
if [[ $(expr "$i" : "$j") -ne 0 ]];then
echo true
fi
case2
i="text stack"
j="stac"
if [[ $(expr "$i" : "$j") -ne 0 ]];then
echo true
fi
case3
i="text stack"
j="ext"
if [[ $(expr "$i" 开发者_如何学C: "$j") -ne 0 ]];then
echo true
fi
It works only in case1. How can I make it work (and echo true) in all cases?
The :
operator for expr is an anchored regex, i.e. will only match at the beginning of the string (as if your regex started with a '^'
).
As you're using bash's [[
builtin operator, I would write this as:
i="text stack"
j="stac"
if [[ "$i" =~ "$j" ]]; then
echo true
fi
=~
means (from the bash manpage) ... the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise.
精彩评论