查找匹配

正则表达式

data="Pi is equal to 3.14"
#[[ =~ ]] takes an extended regex (ERE): there is no \d,
#the class [0-9] instead; the pattern goes into a variable
pattern='[0-9]+\.[0-9]+'

#the pattern on the right goes without quotes:
#"$pattern" in quotes is searched as plain text
if [[ $data =~ $pattern ]]; then
    #BASH_REMATCH[0] is the whole match
    pi=${BASH_REMATCH[0]}
    #pi is "3.14", the text: bash has no fractions
fi

#grep -o prints only the matching part, -E is the same ERE
fromGrep=$(grep -oE "$pattern" <<< "$data")
#fromGrep is "3.14"

echo "pi is $pi"
echo "fromGrep is $fromGrep"