Converts a verbose regex back to compact form, i.e. joined and without comments or unescaped whitespace. Similar to re.VERBOSE in Python.
function verbose_regex --argument-names pattern --description "Converts a \
verbose regex back to compact form, i.e. joined and without comments or \
unescaped whitespace. Similar to re.VERBOSE in Python"
# See https://docs.python.org/2/library/re.html#re.VERBOSE
echo $pattern |
string replace --regex '#.*$' "" |
string replace --all --regex '(^|[^\\\\])\s+' '$1' |
string replace --all --regex '\\\\(\s)' '$1' |
string match --entire --regex . |
string join ""
end
set x (verbose_regex "
\p{L}+ # prefix
[ _ - ] # delimiter
\p{L}+ # suffix
")
echo $x # \p{L}+[_-]\p{L}+
string match --regex $x "verbose_regex123" # verbose_regex
Can cache output to improve performance:
# https://github.com/fish-shell/fish-shell/issues/1799#issuecomment-612673112
function __memoize_underlying_fn --argument-names funcname
echo '__memoize_'$funcname
end
begin
set --local memoize_keys
set --local memoize_values
function memoize --argument-names funcname
set --local memofn (__memoize_underlying_fn $funcname)
functions --copy $funcname $memofn
function $funcname
# See https://stackoverflow.com/a/40019138/12638282
set --local fn (__memoize_underlying_fn (status function))
set --local key $fn'/'$argv # / is an invalid function character in fish
if set --local index (contains -i -- $key $memoize_keys)
echo $__memoize_values[$index]
else
set --local value ($fn $argv)
set --append memoize_keys $key
set --append memoize_values $value
echo $value
end
end
end
end
memoize verbose_regex
This is made available under the terms of the MIT license. For a copy, see https://opensource.org/licenses/MIT.