Last active
August 15, 2019 18:44
-
-
Save psprint/a69177329d6d15bffdd320011aa208da to your computer and use it in GitHub Desktop.
Zsh functions for non-greedy matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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