regex in bash expression

前端 未结 3 682
渐次进展
渐次进展 2021-01-07 12:25

I have 2 questions about regex in bash expression.

1.non-greedy mode

local temp_input=\'\"a1b\", \"d\" , \"45\"\'
if [[ $temp_input =~ \\\".*?\\\         


        
3条回答
  •  攒了一身酷
    2021-01-07 13:13

    For your first question, an alternative is this:

    [[ $temp_input =~ \"[^\"]*\" ]]
    

    For your second question, you can do this:

    temp_input=abcba
    t=${temp_input//b}
    echo "$(( (${#temp_input} - ${#t}) / 1 )) b"
    

    Or for convenience place it on a function:

    function count_matches {
        local -i c1=${#1} c2=${#2}
        if [[ c2 -gt 0 && c1 -ge c2 ]]; then
            local t=${1//"$2"}
            echo "$(( (c1 - ${#t}) / c2 )) $2"
        else
            echo "0 $2"
        fi
    }
    
    count_matches abcba b
    

    Both produces output:

    2 b
    

    Update:

    If you want to see the matches you can use a function like this. You can also try other regular expressions not just literals.

    function find_matches {
        MATCHES=() 
        local STR=$1 RE="($2)(.*)"
        while [[ -n $STR && $STR =~ $RE ]]; do
            MATCHES+=("${BASH_REMATCH[1]}")
            STR=${BASH_REMATCH[2]}
        done
    }
    

    Example:

    > find_matches abcba b
    > echo "${MATCHES[@]}"
    b b
    
    > find_matches abcbaaccbad 'a.'
    > echo "${MATCHES[@]}"
    ab aa ad
    

提交回复
热议问题