Skip to content

Instantly share code, notes, and snippets.

@psprint
Last active August 15, 2019 18:44
Show Gist options
  • Save psprint/a69177329d6d15bffdd320011aa208da to your computer and use it in GitHub Desktop.
Save psprint/a69177329d6d15bffdd320011aa208da to your computer and use it in GitHub Desktop.
Zsh functions for non-greedy matching
# Usage:
# if .smatch "axx" "a*x"; then
# print $REPLY
# fi
# Output:
# ax
# The parameters $match, etc. are also normally available
.smatch() {
local str="$1" pat="$2" retval=1
match=()
: ${(S)str/(#b)(${~pat})/${retval::=0}}
REPLY="${match[1]}"
return $retval
}
# Usage:
# arr=( a1xx ayy a2xx )
# if .smatches ${arr[@]} "a*x"; then
# print -rl $reply
# fi
# Output:
# a1x
# a2x
.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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment