0

When given a string I want to search for a substring which matches two characters (9&0. 0 should be the last character in that substring) and exactly two characters in between them

string="asd20 92x0x 72x0 YX92s0 0xx0 92x0x"
#I want to select substring YX92s0 from that above string

for var in $string
do
if [[ "$var" == *9**0 ]]; then
    echo $var  // Should print YX92s0 only
fi
done

Obviously this above command doesn't work.

4

2 回答 2

1

您将每个元素与模式匹配*9??0。有几种方法可以做到这一点;这是一个使用字符串在子shell中设置位置参数,然后在for循环中迭代它们的方法:

( set -- $string
  for elt; do [[ $elt == *9??0 ]] && { echo "found"; exit; }; done )
于 2013-03-18T21:58:55.903 回答
0
string="asd20 92x0x 72x0 X92s0 0xx0"

if [[ $string =~ [[:space:]].?9.{2}0[[:space:]] ]]; then
    echo "found"
fi

Or better, taking advantage of word spliting :

string="asd20 92x0x 72x0 X92s0 0xx0"

for s in $string; do
    if [[ $s =~ (.*9.{2}0) ]]; then
        echo "${BASH_REMATCH[1]} found"
    fi
done

This is regex with .

于 2013-03-18T21:30:07.807 回答