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:
set __memoize_keys
set __memoize_values
function __memoize_underlying_fn --argument-names funcname
echo '__memoize_'$funcname
end
function memoize --argument-names funcname
functions --copy $funcname (__memoize_underlying_fn $funcname)
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
memoize verbose_regex
This is made available under the terms of the MIT license. For a copy, see https://opensource.org/licenses/MIT.