Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Useful functions for non-greedy matching



Hello,
Zsh supports non greedy matching only in substitutions like //, via
the (S) flag. This however turns out to be not that big problem thanks
to the following functions:

.smatch() {
    local str="$1" pat="$2" retval=1
    match=()
    : ${(S)str/(#b)(${~pat})/${retval::=0}}
    REPLY="${match[1]}"
    return $retval
}

.smatches() {
    local pat="${@[${#}]}" retval=1
    local -a input
    input=( "${@[1,${#}-1]}" ) reply=() match=()
    : "${(S)input[@]//(#b)(${~pat})/${reply[${#reply}+1]::=${match[1]}}${retval::=0}}"
    REPLY="${match[1]}"
return $retval
}

Example usage:
arr=( a1xx ayy a2xx )
if .smatches ${arr[@]} "a*x"; then
    print -rl $reply
fi

Outout:
a1x
a2x

Gist for possible updates:
https://gist.github.com/psprint/a69177329d6d15bffdd320011aa208da

-- 
Sebastian Gniazdowski
News: https://twitter.com/ZdharmaI
IRC: https://kiwiirc.com/client/chat.freenode.net:+6697/#zplugin
Blog: http://zdharma.org



Messages sorted by: Reverse Date, Date, Thread, Author